articles

Home / DeveloperSection / Articles / Exception Handling in C#

Exception Handling in C#

Exception Handling in C#

Shankar M 7263 18-Feb-2013

In this article,we will discuss about Error-Handling in C# and how to use handlers to trap the exception using try/catch.

Exception Handling

In C# Exception is an object that describes an exceptional (i.e., Error) condition that has occurred in piece of code.

When an exception condition arises, an object representing the exception is created and thrown in the method that caused the error. the try method can handle the exception itself, or pass it on. Either way, at some point in the code, the exception is caught and processed.

Exception can be generated at run-time or they can be manually generated by your code.

C# Exception Handling

In C# Exception handling is managed by four Keywords:

1. try

2. catch

3. finally

4. throw

Briefly, how they work

try:

The piece of code that you want to monitor for exception is enclosed with in a try block. The try block can be followed by one or more (multiple) catch blocks. If an exception generates within a try block it is thrown.

catch:

Your code can catch this exception using catch and handle it. The program can have one or more catch section following a try block.

We can write multiple catch statements to handle different type of exceptions if try block raises more than one exception.

finally:

Any code that must be absolutely executed whether an exception is thrown or not is enclosed within the finally block.

For Ex: If a method opens a file, it must be closed whether an exception is raised or not.

throw:

To manually throw an Exception, we use the keyword throw.

General Form of Exception handling block

The Syntax for using try/catch looks like the following:   

            try
            {
                //Piece of code to Monitor for error
            }
            catch (ExceptionType1 exObj1)
            {
                //Handler for ExceptionType1
            }             catch (ExceptionType2 exObj2)
            {
                //Handler for ExceptionType2
            }
            finally
            {
                //block of code to be executed before try block ends

            }     

We can write multiple catch statements to handle different type of exceptions Incase if our try block raises more than one exception in different situations.

 Exception Classes in C#

     Exceptions in c# are represented by classes. Exception classes in c# are primarily directly or indirectly derived from the System.Exception class.

System.Exception

     Some of the exception classes derived from the System.Exception class are

1. System.ApplicationException

2. System.SystemException 

System.ApplicationException 

  The System.ApplicationException class supports exceptions that are generated by the Application programs. The exceptions defined by the programmers should be derived from this class.

Let me explain this to you in the User-Defined exception section.

 System.SystemException

     The System.SystemException class is the base class for all Predefined/System built-in exceptions. Some of the Predefined exceptions:

 

Exception Class
Description

System.IO.IOException

To Handle I/O Errors

System.IndexOutOfRangeException

To Handle errors generated when a method refers to index out of range

System.DivideByZeroException

To Handle error generated when dividing a number by zero.

System.InvalidCastException

To Handle errors generated during type-casting(Converting one type to another)

Uncaught Exceptions

   Before we start how to handle exceptions, Let us see what happens if you don’t handle them, for ex, we try to divide a number by zero. This program intentionally causes a divide by zero error.  

int a = 0;
 int b = 77 / a;


Here is the output generated when the program is executed:

Exception Handling in C#

 When this program is executed, Systems predefined exception is raised and thrown.

The execution of the program stops, because once an exception has been thrown, it must be caught by an Exception handler (usually the catch block). In this piece of code above we have not supplied any exception handler.

Handling Exceptions (Using Try & Catch)

     The error handling blocks are implemented using try, catch, & finally keywords. Following is an example of how to handle the Exception when divide by zero condition occurs.

Handling an exception provides two benefits:

     1. It allows you to fix error.

     2. Prevents program from terminating automatically.

To handle a run-time error, simply enclose the code that you want to monitor inside a try block, following immediately the catch clause that specifies the exception type that you wish to catch.

To illustrate how this can be done, the following program includes a try block and catch clause which processes the DivideByZeroException generated by the division by zero error.

Program:
          try
            {
                int a = 0;
                int b = 77 / a; // Once executing this control is transferred to the catch block
                MessageBox.Show("After Executing.."); // This Statement is not executed
            }            catch (DivideByZeroException ex)
            {
                MessageBox.Show(ex.Message);
            }

When the program is executed, we will have a message displayed Attempted to divide by zero.

When the control reaches the int b = 77 / a  it raises the exception and is thrown. The catch handler traps this exception and the message Attempted to divide by zero is displayed.

Multiple catch Clauses

In some cases, more than one exception could be raise by a single piece of code. To handle this type of situation, you can specify two or more catch clauses, each having a different type to handle different exceptions.

When an exception is thrown, each catch is inspected in order and the first one whose type matches that of the exception is executed. After one catch statement executes, the others are bypasses and execution continues after the try/catch block.

To illustrate how this is done we will look the following program:      

           try

            {
                int a = 2;
                int b = 77 / a;
                int[] arr = {1};
                arr[27] = 100;
            }

            catch (DivideByZeroException ex)
            {
                MessageBox.Show(ex.Message);
            }
            catch (IndexOutOfRangeException ex1)
            {
                MessageBox.Show(ex1.Message);
            }     

The program causes a divide by zero exception if a is assigned a value 0.

It will survide the division if you assign a to something larger than zero.

But, the above program will cause IndexOutOfRangeException since the int array arr has a length of 1, yet we attempt to assign value to c[27].

 The below program contains an error  

/* A subclass must come before it Superclass in a series
 * of catch statments. If not complile-error will result.
 */
           try
            {
                int a = 0;
                int b = 77 / a;
            }
            catch (SystemException ex)
            {
                MessageBox.Show(ex.Message);
            }
            catch (DivideByZeroException ex)
            {
                MessageBox.Show(ex.Message);
            }

If you try to compile this program, you will receive an error message stating that

A previous catch clause already catches all exceptions of this or of a super type ('System.SystemException')

Syntax notification Squiggles underlines code that wont code or that might cause an error before we compile the project here (DivideByZeroException)

Since DivideByZeroException is a subclass of SystemException, the first catch statement will handle all Exception-bases errors including DivideByZeroException. This means the second catch staement will never execute.

To fix the problem reverse the order of catch statements as,  

try

            {
                int a = 0;
                int b = 77 / a;
            }
            catch (DivideByZeroException ex)
            {
                MessageBox.Show(ex.Message);
            }
            catch (SystemException ex)
            {
                MessageBox.Show(ex.Message);
            }

When you use multiple catch statement, it is important to remember that exception subclass must come before any of their super class. This is because a catch statement that uses a super class will catch exceptions of that type plus any of it subclasses.

Thus, a subclass would never be reached if it comes after its super class.

User-Defined Exceptions

     We have only been catching exceptions that are thrown so far. However, it is also possible to define your program to throw an exception explicitly.

The general form of throwing a User-Defined exception is

throw UserDefinedInstance;     

Here, UserDefinedInstance must be an object of type UserDefinedException or a subclass of UserDefinedException class.

User-Defined Exception classes are derived from ApplicationException class.

Here is example to illustrate how to create User-Defined exceptions:

Program:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ErrorHandling{
    public partial class frmErrorHandler : Form
    {
        int a = 0;
        public frmErrorHandler()
        {
            InitializeComponent();
        }

        private void frmErrorHandler_Load(object sender, EventArgs e)
        {             try
            {
                if (a == 0)
                {
                    throw (new ValueisZeroException("Cannot be assigned value Zero"));
                }
            }
            catch (ValueisZeroException ex)
            {
                MessageBox.Show(ex.Message);
            }
        } 

        public class ValueisZeroException : ApplicationException
        {             public ValueisZeroException(string txt) : base(txt)
            {
            }

        }
}
}
Conclusion:

In this article I have discussed what are Exception handlers in C# and how to trap errors using try/catch block and their behavior when we use multiple catch statements to handle errors and lastly, how to create User-Defined exceptions


c# c# 
Updated 27-Nov-2019

Leave Comment

Comments

Liked By