C# Tutorial 18 - Exception Handling in C#
The main idea behind exception handling is to handle the runtime errors and prevent program from being crash. An unhandled exception in code results in crashing of the code. For example, if you are performing division of two variable and if divisor is zero then an exception raised. Another example can be of accessing a file which does not exists on file system. Exception terminates the normal flow of application as it terminates the application. Exception handling allows to continue normal flow of application by handling the exception. In .NET framework, there are numerous classes available for exceptions. Exception class is base of these classes and if you are creating a new exception, it will inherit the Exception class. An example of exception is following snippet of code:
int[] arr = new arr[3];
Console.WriteLine(arr[5]);
Console.WriteLine(arr[5]);
try { // place the code here which may raise exception } catch(Exception type) { // handle the exception } finally { // final code }
try blockIt contains the code which may raise the exception or is suspicious of raising an exception. If exception occurs, respective exception block will be executed.
catch blockIt is the block where exception is actually handled and it requires exception object as parameter which is used for getting information about exception. If you are not sure about exact type of exception you can pass object of Exception class You can log or audit the what you want to do in order to handle the exception.
finally blockFinally block gets executed whether exception occurs or not. The main idea behind finally is to release the resources being utilized like database connection of closing the file stream.
Now exception raised in above example can be handled as follows:
try
{
int x = 10;
int y = 0;
Console.WriteLine(x/y);
}
catch(Exception ex)
{
Console.Write(ex.Message);
}
{
int x = 10;
int y = 0;
Console.WriteLine(x/y);
}
catch(Exception ex)
{
Console.Write(ex.Message);
}
Now lets see an example of using finally block.
FileInfo file = null;
try
{
Console.Write("Enter a file name");
string fileName = Console.ReadLine();
file = new FileInfo(fileName);
file.AppendText("Hello There")
}
catch(Exception ex)
{
Console.WriteLine(ex.Message );
}
finally
{
file = null;
}
You can also use multiple catch blocks with a single try block like example below.
try
{
//code that may raise an exception
}
catch(DivideByZeroException ex)
{
Console.WriteLine("Division By Zero");
}
catch(InvalidOperationException ex)
{
Console.WriteLine("Invalid Operation Performed");
}