Exception Handling provides a way to avoid the occurrence of the errors. To learn exception handling, one have to know that the location where there is a chance to occur an error. The Exception is an object. Exception Class is the root class for all type of exceptions.
First of all, one should know the Built-in Exceptions in the .Net framework.
Types
There are three types of Exception Handling Mechanisms.
Using try, catch, throw and finally
Logical Handling
User-defined Exceptions
Using try, catch, throw and finally
Description
This mechanism is used by many people. By using this try, catch, throw and finally blocks, one can handle errors.
try: try block contains the code that may expect to cause errors.
catch: Raised exception will be handled in the catch block. Simply catches the exception and
throw: throws an exception which is raised.
Finally: Contains the statements which to be executed.
one can write any number of exceptions for so single try block.
Syntax
The below code shows you the syntax.
[csharp]
try
{
//code which may cause error
}
catch(ExceptionName e1)
{
//error handling code
}
catch(exceptionName e2)
{
//error handling code
}
finally
{
// statements finally executes
}
[/csharp]
Logical Handling
Description
In this mechanism, one can write code in the logic where that may cause an error.For example
Example
See the below example code.
[csharp]
private void Form1_Load(object sender, EventArgs e)
{
int a, b, Result;
a = 12;
b = 0;
Result = a / b; //cause divide by zero error
}
[/csharp]
To avoid this error, one can use built-in exception or logical handling, and can write the above code as below. Then the error not occurred.
[csharp]
private void Form1_Load(object sender, EventArgs e)
{
int a, b, Result;
a = 12;
b = 0;
if(b==0)
{
MessageBox.Show("invalid operation");
}
else {
Result = a / b;
}
}
[/csharp]
It will display a user-friendly message when an error occurs.
User-defined Exceptions
Description
User-defined Exceptions are created by the user. Here, one can use throw keyword to raise the exception.
User-defined Exceptions are also called as Application Exceptions. Application Exception is a class which contains all these type of exceptions.