C# Exception Handling
Definition:"EXCEPTION IS A RUNTIME ERROR WHICH ARISES BECAUSE OF ABNORMALCONDITION INA CODE SEQUENCE. " In C# Exception is a class in the systemnamespace. An object of an exception is that describe the exceptionalconditions occur in a code That means, we are catching an exception,creating an object of it, and then throwing it. C# supports exceptionsin a very much the same way as Java and 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 tookplace. This makes them very suitable for library or system code, whichcan 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?catchstatements. Code which may give rise to exceptions is enclosed in a tryblock , which is followed by one or more catch blocks. Well if we don'twrite like such we get errors like as follows :
class A {
static void Main() {
catch {
}
}
}
TEMP.cs(3,5): error CS1003: Syntax error, 'try' expected
class A {
static void Main() {
finally {
}
}
}
TEMP.cs(3,5): error CS1003: Syntax error, 'try' expected
class A {
static void Main() {
try {
}
}
}
TEMP.cs(6,3): error CS1524: Expected catch or finally
The try block contains the code segmentexpected to raise an exception. This block is executed until anexception is thrown The catch block contains the exception handler.This block catches the exception and executes the code written in theblock. If we do not know what kind of exception is going to be thrownwe can simply omit the type of exception. We can collect it inException object as shown in the following program:
int a, b = 0 ;
Console.WriteLine( "My program starts " ) ;
try
{
a = 10 / b;
}
catch ( Exception e )
{
Console.WriteLine ( e ) ;
}
Console.WriteLine ( "Remaining program" ) ;
The output of the program is:
My program starts
System.DivideByZeroException: Attempted to divide by zero.atConsoleApplication4.Class1.Main(String[] args) in d:\dont delete\c#(csharp)\swapna\programs\consoleapplication4\consoleapplication4\class1.cs:line51
Remaining program
The exception 'Divide by zero' was caught, butthe execution of the program did not stop. There are a number ofexception classes provided by C#, all of which inherit from theSystem.Exception class. Following are some common exception classes.
| Exception Class | Cause |
| SystemException | A failed run-time check;used as a base class for other. |
| AccessException | Failure to access a type member, such as a method or field. |
| ArgumentException | An argument to a method was invalid. |
| ArgumentNullException | A null argument was passed to a method that doesn't accept it. |
| ArgumentOutOfRangeException | Argument value is out of range. |
| ArithmeticException | Arithmetic over – or underflow has occurred. |
| ArrayTypeMismatchException | Attempt to store the wrong type of object in an array. |
| BadImageFormatException | Image is in the wrong format. |
| CoreException | Base class for exceptions thrown by the runtime. |
| DivideByZeroException | An attempt was made to divide by zero. |
| FormatException | The format of an argument is wrong. |
| IndexOutOfRangeException | An array index is out of bounds. |
| InvalidCastExpression | An attempt was made to cast to an invalid class. |
| InvalidOperationException | A method was called at an invalid time. |
| MissingMemberException | An invalid version of a DLL was accessed. |
| NotFiniteNumberException | A number is not valid. |
| NotSupportedException | Indicates sthat a method is not implemented by a class. |
| NullReferenceException | Attempt to use an unassigned reference. |
| OutOfMemoryException | Not enough memory to continue execution. |
| StackOverflowException | A stack has overflown. |
The finally block is used to do all the cleanup code. It does not support the error message, but all the codecontained in the finally block is executed after the exception israised. We can use this block along with try-catch and only with catchtoo.
The finally block is executed even if theerror is raised. Control is always passed to the finally blockregardless of how the try blocks exits.
This is shown in the following example:
int a, b = 0 ;
Console.WriteLine( "My program starts" ) ;
try
{
a = 10 / b;
}
catch ( InvalidOperationException e )
{
Console.WriteLine ( e ) ;
}
catch ( DivideByZeroException e)
{
Console.WriteLine ( e ) ;
}
finally
{
Console.WriteLine ( "finally" ) ;
}
Console.WriteLine ( "Remaining program" ) ;
The output here is:
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
But then what's the difference? We could have written
Console.WriteLine ("finally");
after the catch block, and not write the finally block at all. Writingfinally did not make much of a difference. Anyway the code writtenafter catch gets executed.
The answer to this is not clear in this program.
It will be clear when we see the try-finally and the throw statement.
Consider the following code snippet
int a, b
= 0 ;
/>Console.WriteLine( "My program starts" )
try
{
a = 10 / b;
}
finally
{
Console.WriteLine ( "finally" ) ;
}
Console.WriteLine ( "Remaining program" ) ;
Here the output is
My program starts
Exception occurred: System.DivideByZeroException: Attempted to divideby zero.at ConsoleApplication4.Class1.Main(String[] args) in d:\dontdelete\c# (csharp)\swapna\programs\consoleapplication4\consoleapplication4\class1.cs:line51
finally
Note that "Remaining program" is not printed out. Only "finally" is printed which is written in the finally block.
The throw statement throws an exception. Athrow statement with an expression throws the exception produced byevaluating the expression. A throw statement with no expression is usedin the catch block. It re-throws the exception that is currently beinghandled by the catch block.
Consider the following program:
int a, b = 0 ;
Console.WriteLine( "My program starts" ) ;
try
{
a = 10 / b;
}
catch ( Exception e)
{
throw
}
finally
{
Console.WriteLine ( "finally" ) ;
}
The output here is:
My program starts
Exception occurred: System.DivideByZeroException: Attempted to divideby zero.at ConsoleApplication4.Class1.Main(String[] args) in d:\dontdelete\c#(csharp)\swapna\programs\consoleapplication4\consoleapplication4\class1.cs:line55
finally
This shows that the exception is re-thrown.Whatever is written in finally is executed and the program terminates.Note again that "Remaining program" is not printed.












No comments yet... Be the first to leave a reply!