Exception Handling in C# with Example
Exceptions are unexpected errors generated by the CLR. It is very common that while executing your application you encounter some error and later you fix it by knowing the reason behind it. There are bunch of predefined exceptions in the DotNet framework like FileNotFound, DivideByZero, FormatException etc. However, name of these exceptions is pretty much informative for the end user, but most of the users don’t even know what they actually mean. It is a responsibility of the developer to fix all these errors by debugging the application and provide some meaningful info to the end user.
There are numerous reasons why you should handle these exceptions. These exceptions can reveal some of the hard coded information to the end user, which you don’t want him to know about. For example, an application which connects to the server using hard coded user name and password may throw an exception if server is not found or server is busy. Also, if your application throws an exception, your program execution stops at that point which means your application will not be able to release any system related resources. A very common example for this scenario is StreamReader and StreamWriter class.
To handle such exceptions, we make use of Try and Catch block. Try block contains a piece of code, we want to execute and Catch block contains the code, which we want to execute in case of an exception to give a meaningful info to the end user in the form of a message. You can also write a code to generate a log for that exception, so that user can send it you and it will help you to track the error. Exception class contains some properties such as Message, StackTrace etc, which will help you to obtain some relative information about the error. StackTrace will give you the info about at which line the error has occurred in the code file. Message will give you same basic info about the error. To see all predefined dotnet framework exceptions, you can use keyboard shortcut CTRL+ALT+E.
Example of DivideByZero Exception
using System; namespace Hello { class Program { static void Main(string[] args) { int num1 = 10; int num2 = 0; try { int num3 = num1 / num2; Console.WriteLine(num3); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } }
Output:
Attempted to divide by zero.
Press any key to continue . . .
All the exceptions directly or indirectly inherit from Exception class. To handle DivideByZero exception, you can directly use it by its name in the Catch block. You can also create multiple catch blocks to handle different type of exceptions. The very important point to remember here is, you always use Exception class in very last Catch block to handle all other general exceptions. If you use it in very first Catch block, then it will never reach to your next Catch block and also there will be a compile time error if you do so.
using System; namespace Hello { class Program { static void Main(string[] args) { int num1 = 10; int num2 = 0; try { int num3 = num1 / num2; Console.WriteLine(num3); } catch (DivideByZeroException dv) { Console.WriteLine(dv.Message); } catch(Exception ex) { Console.WriteLine(ex.Message); } } } }
After Try and Catch block, there is another block called Finally block. After encountering an exception, your program execution will be stopped, but any code inside the Finally block will always execute, no matter how many exceptions will be there. Finally block is normally used to close the handles of other classes like StreamReader, StreamWriter etc and release system related resources associated to those classes. The point to remember here is, you must check whether the reference variable is null or not before closing the handle.
using System; namespace Hello { class Program { static void Main(string[] args) { int num1 = 10; int num2 = 0; try { int num3 = num1 / num2; //Not Executed Console.WriteLine(num3); } catch (DivideByZeroException dv) { Console.WriteLine(dv.Message); } catch(Exception ex) { Console.WriteLine(ex.Message); } finally { //Executed Console.WriteLine("This is Finally block"); } } } }
Output:
Attempted to divide by zero.
This is Finally block
Press any key to continue . . .