Here Mohammad Shaik provided a short tutorial with example, about Exception Handling in C#.
Before going into detail, I must say the usefulness of knowing and performing exception handling :
- They cannot be ignored, as if calling code does not handle the error, it causes program termination.
- They do not need to be to be handled at the point where error took place. This makes them very suitable for library or system code, which can signal an error and leave us to handle it.
- They can be used when passing back a return value cannot be used.
Exceptions are handled by using try...catch statements.
Exceptions is enclosed in a try block, which is followed by one or more catch blocks. Well if you don't use try...catch, you could get errors like the following:
Syntax
Assuming a block will raise and exception, a method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following:
try
{
// statements causing exception
}
catch( ExceptionName EN1 )
{
// Error handling code
}
catch( ExceptionName EN2 )
{
// Error handling code
}
catch( ExceptionName EN3 )
{
// Error handling code
}
finally
{
// Statements to be executed
}
Example:
int a, b = 0 ;
Console.WriteLine( "My First Application" ) ;
try
{
a = 10 / b;
}
catch ( Exception ex )
{
Console.WriteLine ( ex ) ;
}
Console.WriteLine ( "Remaining program" ) ;
My program starts
System.DivideByZeroException: Attempted to divide by zero.
at ConsoleApplication4.Class1.Main(String[] args) in
d:\dont delete\c#(c sharp)\swapna\programs\consoleapplication4\
consoleapplication4\class1.cs:line 51
Remaining program
Exception Classes in C#
C# exceptions are represented by classes. The exception classes in C# are mainly directly or indirectly derived from the
System.Exception class. Some of the exception classes derived from the System.Exception class are the System.ApplicationException and System.SystemException classes.
The
System.ApplicationException class supports exceptions generated by application programs. So the exceptions defined by the programmers should derive from this class.
The
System.SystemException class is the base class for all predefined system exception.
The following table provides some of the predefined exception classes derived from the Sytem.SystemException class:
Exception Class | Description |
System.IO.IOException | Handles I/O errors. |
System.IndexOutOfRangeException | Handles errors generated when a method refers to an array index out of range. |
System.ArrayTypeMismatchException | Handles errors generated when type is mismatched with the array type. |
System.NullReferenceException | Handles errors generated from deferencing a null object. |
System.DivideByZeroException | Handles errors generated from dividing a dividend with zero. |
System.InvalidCastException | Handles errors generated during typecasting. |
System.OutOfMemoryException | Handles errors generated from insufficient free memory. |
System.StackOverflowException | Handles errors generated from stack overflow. |
Example:
int a, b = 0 ;
Console.WriteLine( "My First Application" ) ;
try
{
a = 10 / b;
}
catch ( InvalidOperationException e )
{
Console.WriteLine ( e ) ;
}
catch ( DivideByZeroException e)
{
Console.WriteLine ( e ) ;
}
finally
{
Console.WriteLine ( "finally" ) ;
}
Console.WriteLine ( "Remaining program" ) ;
My program starts
System.DivideByZeroException: Attempted to divide by zero.
at ConsoleApplication4.Class1.Main(String[] args) in
d:\dont delete\c# (c sharp)\swapna\programs\consoleapplication4\
consoleapplication4\class1.cs:line 51
finally
Remaining program
Creating User-Defined Exceptions
You can also define your own exception. User-defined exception classes are derived from the ApplicationException class. The following example demonstrates this:
using System;
namespace UserDefinedException
{
class TestTemperature
{
static void Main(string[] args)
{
Temperature temp = new Temperature();
try
{
temp.showTemp();
}
catch(TempIsZeroException e)
{
Console.WriteLine("TempIsZeroException: {0}", e.Message);
}
Console.ReadKey();
}
}
}
public class TempIsZeroException: ApplicationException
{
public TempIsZeroException(string message): base(message)
{
}
}
public class Temperature
{
int temperature = 0;
public void showTemp()
{
if(temperature == 0)
{
throw (new TempIsZeroException("Zero Temperature found"));
}
else
{
Console.WriteLine("Temperature: {0}", temperature);
}
}
}
When the above code is compiled and executed, it produces the following result:
div id="Div14" class="codeBG contentColor">
TempIsZeroException: Zero Temperature found
Throwing Objects
You can throw an object if it is either directly or indirectly derived from the System.Exception class. You can use a throw statement in the catch block to throw the present object as:
Catch(Exception e)
{
...
Throw e
}
I hope this page will helps to learn Exception Handling in C#. Thanks.