C# provides managed exception handling.This means that we don’t have to manually check the code for exceptions.Instead execution is automatically transfered to the appropriate part.
An Exception is an error which happens during program execution or runtime.Exception handling allows us to efficiently manage the unexpected behaviors during program execution.For example if we try to assign string value to an integer value during runtime then an exception occurs.
When an exception occurs an object of type derived from the Exception class is created and thrown.Exception is a class in the System namespace. All the exceptions in .NET framework derive from the Exception class.If we need to create our custom exception class then we can derive our class from the Exception class.
Exception handling in C#
C# provides structured exception handling.This means that the exceptions are monitored using the well defined exception handling constructs or keywords. Following are the exception handling keywords
- try
- catch
- finally
try
try keyword defines the try block . try block contains the code which we want to monitor for exceptions.If an exception occurs inside the try block an object of type exception is created and thrown.
catch try block is followed by the catch block.catch keyword defines the catch block.The exception that is thrown by the catch block is handled in the catch block.This mean when exception occurs the control is automatically passed to the catch block.
As there can me multiple catch blocks so the type of exception object determines which catch block will execute.
finally finally block is the last block.This is defined using the finally keyword. Unlike catch and try blocks finally block defined the code which is sure to execute each time.This block usually defined the clean up code such disposing objects.
In the following code there are two catch blocks.The first catch block will handle the exceptions of type Exception1 while the second catch block will handle exceptions of type Exception2
try { //code to monitor for exceptions } catch(Exception1 exc1) { //exception handling code } catch(Exception2 exc2) { //exception handling code } finally { //clean up code }
Causes of exceptions
- Exceptions can be automatically thrown by the .NET
- Exceptions can be thrown by creating and throwing an object of type exception.
Inbuilt Exception classes
There are few inbuilt exception classes provided by the Framework.These are used for handling different types of exceptions.Some of the commonly used exception classes are:
IndexOutOfRangeException thrown when array refers to an invalid index.
NullReferenceException thrown when a null object is referenced
DivideByZeroException thrown when an attempt is made to divide by zero.
InvalidCastException thrown when the specified cast is invalid.
Leave a Reply