How to handle exceptions?
The procedure of handling exceptions are explained
The .NET Framework provides a systematic method to handle the exceptions. This is known as Structured Exception Handling. This technique allows the developer to anticipate the situations where exceptions may occur and write code to handle them in such a way that the application can continue to work and the user is shown a friendly message that something is wrong.
In C#, we have three keywords: try, catch and finally - to implement the exception handling.
The structure of the exception handling mechanism in C# is as follows:
try
{
write the code which can result in exception
}
catch
{
write the code that will execute if exception occurs inside the try block
}
finally
{
this part will execute whether any exceptions occur or not.
}
The code inside the `try' block is the code where we anticipate an exception to occur. If there is an exception, the program will look inside the `catch' block for the code that deals with the exception. The `finally' block is optional but if it is present, the code inside it will always run.
Let us modify our code to see how this all works:
static void Main(string[] args) { int num1, num2, answer; try { Console.WriteLine("Please enter the first number"); num1 = int.Parse(Console.ReadLine()); Console.WriteLine("Now enter the second number"); num2 = int.Parse(Console.ReadLine()); answer = num1 / num2;
Console.WriteLine("The result is {0}", answer); } catch { Console.WriteLine("Some error occured"); } }
We have put the code to enter the values, the process to calculate the result and then displaying the output inside the try block. This is because we anticipate that this part of the code can result in an exception. Inside the catch block, we have used an output statement to display a message.
When we run the program with valid inputs, the program works fine. However, if we enter invalid input, instead of displaying cryptic messages like before, our program displays an easy to understand error message.
We can be more specific with the errors. Let us modify the code once again:
static void Main(string[] args) { int num1, num2, answer; try { Console.WriteLine("Please enter the first number"); num1 = int.Parse(Console.ReadLine()); Console.WriteLine("Now enter the second number"); num2 = int.Parse(Console.ReadLine()); answer = num1 / num2;
Console.WriteLine("The result is {0}", answer); } catch(Exception ex) { Console.WriteLine("Some error occured:" + ex.Message); } }
In this case, we are using an Exception object named `ex' in the catch block. The name of the object can be anything, but we have just used `ex' in this example. This Exception object has a property called `Message'. This property provides a description of the exception that occurred. When we display the output in the catch block, the description of the exception will be added to the string: "Some error occurred".
Test the program by running it and providing invalid input:
Not bad. But we can modify it further to make it better:
static void Main(string[] args) { int num1, num2, answer;
try { Console.WriteLine("Please enter the first number"); num1 = int.Parse(Console.ReadLine()); Console.WriteLine("Now enter the second number"); num2 = int.Parse(Console.ReadLine());
answer = num1 / num2;
Console.WriteLine("The result is {0}", answer); } catch (DivideByZeroException ex) { Console.WriteLine("Cannot Divide By Zero"); } catch (FormatException ex) { Console.WriteLine("Can only take integer inputs"); } catch (Exception ex) { Console.WriteLine("Some error occured:" + ex.Message); } finally { Console.WriteLine("Thanks for using the program"); } }
We have used three catch blocks in this code. It is legal to use multiple catch blocks. If we can anticipate the different types of exceptions that can occur in our code, we can write separate catch blocks for each type of exception.
The first catch block uses an object of DivideByZeroException. If the program gets the second input as zero, this catch block will be used and the message inside the catch block will be displayed. All other catch blocks will be ignored and then the message inside the finally block will be displayed. Remember that the finally block, if present, will always execute.
The second catch block uses an object of FormatException. If the program gets the input other than integers, this catch block will be used and the message inside the catch block will be displayed. All other catch blocks will be ignored and then the message inside the finally block will be displayed.
The third catch block is a generalized one. It will catch all the exceptions not covered by the earlier catch blocks and display the related messages. It is important to place this generalized catch block after all the specific catch blocks. Otherwise, it will catch all the exceptions early on and the catch blocks for the specific exceptions will be ignored.
The finally block will always execute whether an exception occurs or not.



