Exception Handling in C#

C# Exception handling is a mechanism in .NET to detect and handle run time errors. The try..catch block is used to implement exception handling in C#. In try..catch..finally block, finally is used for code cleanup. Code sample for multiple try catch block.

Exception handling in C# and .NET framework, suppoted by the try catch and finaly block is a mechanism to detect and handle run-time errors in code. The .NET framework provides built-in classes for common exceptions. The exceptions are anomalies that occur during the execution of a program. They can be because of user, logic or system errors. If a user (programmer) does not provide a mechanism to handle these anomalies, the .NET runtime environment provide a default mechanism, which terminates the program execution. 
 

try..catch..finally

 
C# provides three keywords try, catch and finally to implement exception handling. The try encloses the statements that might throw an exception whereas catch handles an exception if one exists. The finally can be used for any cleanup work that needs to be done.
 
Try..catch..finally block example:
  1. try
  2. {
  3. // Statement which can cause an exception.
  4. }
  5. catch(Type x)
  6. {
  7. // Statements for handling the exception
  8. }
  9. finally
  10. {
  11. //Any cleanup code
  12. }
If any exception occurs inside the try block, the control transfers to the appropriate catch block and later to the finally block. 
 
But in C#, both catch and finally blocks are optional. The try block can exist either with one or more catch blocks or a finally block or with both catch and finally blocks.
 
If there is no exception occurred inside the try block, the control directly transfers to finally block. We can say that the statements inside the finally block is executed always. Note that it is an error to transfer control out of a finally block by using break, continue, return or goto.
 
In C#, exceptions are nothing but objects of the type Exception. The Exception is the ultimate base class for any exceptions in C#. The C# itself provides couple of standard exceptions. Or even the user can create their own exception classes, provided that this should inherit from either Exception class or one of the standard derived classes of Exception class like DivideByZeroExcpetion to ArgumentException etc.
 

Uncaught Exceptions

 
The following program will compile but will show an error during execution. The division by zero is a runtime anomaly and program terminates with an error message. Any uncaught exceptions in the current context propagate to a higher context and looks for an appropriate catch block to handle it. If it can't find any suitable catch blocks, the default mechanism of the .NET runtime will terminate the execution of the entire program.
  1. //C#: Exception Handling   
  2. //Author: rajeshvs@msn.com  
  3. using System;  
  4. class MyClient  
  5. {  
  6.     public static void Main()  
  7.     {  
  8.         int x = 0;  
  9.         int div = 100/x;  
  10.         Console.WriteLine(div);  
  11.      }  
  12. }
The modified form of the above program with exception handling mechanism is as follows. Here we are using the object of the standard exception class DivideByZeroException to handle the exception caused by division by zero.
  1. //C#: Exception Handling
  2. using System;
  3. class MyClient
  4. {
  5.     public static void Main()
  6.     {
  7.         int x = 0;
  8.         int div = 0;
  9.         try
  10.         {
  11.             div = 100 / x;
  12.             Console.WriteLine("This linein not executed");
  13.         }
  14.         catch (DivideByZeroException)
  15.         {
  16.             Console.WriteLine("Exception occured");
  17.         }
  18.         Console.WriteLine($"Result is {div}");
  19.     }
  20. } 
Result from above code is show below:
 
exception handling in c#  
 
In the above case, the program do not terminate unexpectedly. Instead, the program control passes from the point where exception occurred inside the try block to the catch blocks. If it finds any suitable catch block, executes the statements inside that catch and continues with the normal execution of the program statements.
 
If a finally block is present, the code inside the finally block will get also be executed. 
  1. //C#: Exception Handling
  2. using System;
  3. class MyClient  
  4. {
  5.     public static void Main()
  6.     {
  7.         int x = 0;
  8.         int div = 0;
  9.         try
  10.         {
  11.             div = 100/x;
  12.             Console.WriteLine("Not executed line");
  13.         }
  14.         catch(DivideByZeroException)
  15.         {
  16.             Console.WriteLine("Exception occured");
  17.         }
  18.         finally
  19.         {
  20.             Console.WriteLine("Finally Block");
  21.         }
  22.         Console.WriteLine($"Result is {div}");
  23.     }
  24. }
Remember that in C#, the catch block is optional. The following program is perfectly legal in C#.
  1. //C#: Exception Handling
  2. using System;
  3. class MyClient
  4. {
  5.     public static void Main()
  6.     {
  7.         int x = 0;
  8.         int div = 0;
  9.         try
  10.         {
  11.             div = 100/x;
  12.             Console.WriteLine("Not executed line");
  13.         }
  14.         finally
  15.         {
  16.             Console.WriteLine("Finally Block");
  17.         }
  18.         Console.WriteLine($"Result is {div}");
  19.     }
  20. }
But in this case, since there is no exception handling catch block, the execution will get terminated. But before the termination of the program statements inside the finally block will get executed. In C#, a try block must be followed by either a catch or finally block.
 

Multiple Catch Blocks 

 
A try block can throw multiple exceptions, which can handle by using multiple catch blocks. Remember that more specialized catch block should come before a generalized one. Otherwise the compiler will show a compilation error. 
  1. //C#: Exception Handling: Multiple catch
  2. using System;
  3. class MyClient
  4. {
  5.     public static void Main()
  6.     {
  7.         int x = 0;
  8.         int div = 0;
  9.         try
  10.         {
  11.             div = 100 / x;
  12.             Console.WriteLine("Not executed line");
  13.         }
  14.         catch (DivideByZeroException de)
  15.         {
  16.             Console.WriteLine("DivideByZeroException");
  17.         }
  18.         catch (Exception)
  19.         {
  20.             Console.WriteLine("Exception");
  21.         }
  22.         finally
  23.         {
  24.             Console.WriteLine("Finally Block");
  25.         }
  26.         Console.WriteLine($"Result is {div}");
  27.     }
  28. }

Catching all Exceptions

 
By providing a catch block without brackets or arguments, we can catch all exceptions occurred inside a try block. Even we can use a catch block with an Exception type parameter to catch all exceptions happened inside the try block since in C#, all exceptions are directly or indirectly inherited from the Exception class.
  1. //C#: Exception Handling: Handling all exceptions  
  2. using System;  
  3. class MyClient  
  4. {  
  5.     public static void Main()  
  6.     {  
  7.         int x = 0;  
  8.         int div = 0;  
  9.         try  
  10.         {  
  11.             div = 100 / x;  
  12.             Console.WriteLine("Not executed line");  
  13.         }  
  14.         catch  
  15.         {  
  16.             Console.WriteLine("oException");  
  17.         }  
  18.         Console.WriteLine($"Result is {div}");  
  19.     }  
  20. }
The following program handles all exception with Exception object. 
  1. //C#: Exception Handling: Handling all exceptions
  2. using System;
  3. class MyClient
  4. {
  5.     public static void Main()
  6.     {
  7.         int x = 0;
  8.         int div = 0;
  9.         try
  10.         {
  11.             div = 100 / x;
  12.             Console.WriteLine("Not executed line");
  13.         }
  14.         catch (Exception)
  15.         {
  16.             Console.WriteLine("oException");
  17.         }
  18.         Console.WriteLine($"Result is {div}");
  19.     }
  20. }

Throwing an Exception

 
In C#, it is possible to throw an exception programmatically. The 'throw' keyword is used for this purpose. The general form of throwing an exception is as follows. 
  1. throw exception_obj; 
For example, the following statement throws an ArgumentException explicitly.
  1. throw new ArgumentException("Exception");
  2.   
  3. //C#: Exception Handling:
  4. using System;
  5. class MyClient
  6. {
  7.     public static void Main()
  8.     {
  9.         try
  10.         {
  11.             throw new DivideByZeroException("Invalid Division");
  12.         }
  13.         catch (DivideByZeroException)
  14.         {
  15.             Console.WriteLine("Exception");
  16.         }
  17.         Console.WriteLine("LAST STATEMENT");
  18.     }  
  19. }

Re-throwing an Exception

 
The exceptions, which we caught inside a catch block, can re-throw to a higher context by using the keyword throw inside the catch block. The following program shows how to do this. 
  1. //C#: Exception Handling: Handling all exceptions
  2. using System;
  3. class MyClass
  4. {
  5.     public void Method()
  6.     {
  7.         try
  8.         {
  9.             int x = 0;
  10.             int sum = 100 / x;
  11.         }
  12.         catch (DivideByZeroException)
  13.         {
  14.             throw;
  15.         }
  16.     }
  17. }
  18. class MyClient
  19. {
  20.     public static void Main()
  21.     {
  22.         MyClass mc = new MyClass();
  23.         try
  24.         {
  25.             mc.Method();
  26.         }
  27.         catch (Exception)
  28.         {
  29.             Console.WriteLine("Exception caught here");
  30.         }
  31.         Console.WriteLine("LAST STATEMENT");
  32.     }
  33. }

Standard Exceptions

 
There are two types of exceptions: exceptions generated by an executing program and exceptions generated by the common language runtime. System.Exception is the base class for all exceptions in C#. Several exception classes inherit from this class including ApplicationException and SystemException. These two classes form the basis for most other runtime exceptions. Other exceptions that derive directly from System.Exception include IOException, WebException etc.
 
The common language runtime throws SystemException. The ApplicationException is thrown by a user program rather than the runtime. The SystemException includes the ExecutionEngineException, StaclOverFlowException etc. It is not recommended that we catch SystemExceptions nor is it good programming practice to throw SystemExceptions in our applications.
  • System.OutOfMemoryException
  • System.NullReferenceException
  • Syste.InvalidCastException
  • Syste.ArrayTypeMismatchException
  • System.IndexOutOfRangeException        
  • System.ArithmeticException
  • System.DevideByZeroException
  • System.OverFlowException 

User-defined Exceptions

 
In C#, it is possible to create our own exception class. But Exception must be the ultimate base class for all exceptions in C#. So the user-defined exception classes must inherit from either Exception class or one of its standard derived classes.
  1. //C#: Exception Handling: User defined exceptions
  2. using System;
  3. class MyException : Exception
  4. {
  5.     public MyException(string str)
  6.     {
  7.         Console.WriteLine("User defined exception");
  8.     }
  9. }
  10. class MyClient
  11. {
  12.     public static void Main()
  13.     {
  14.         try
  15.         {
  16.             throw new MyException("RAJESH");
  17.         }
  18.         catch (Exception)
  19.         {
  20.             Console.WriteLine("Exception caught here" + e.ToString());
  21.         }
  22.         Console.WriteLine("LAST STATEMENT");
  23.     }
  24. }

Design Guidelines

 
Exceptions should be used to communicate exceptional conditions. Don't use them to communicate events that are expected, such as reaching the end of a file. If there's a good predefined exception in the System namespace that describes the exception condition-one that will make sense to the users of the class-use that one rather than defining a new exception class and put specific information in the message. Finally, if code catches an exception that it isn't going to handle, consider whether it should wrap that exception with additional information before re-throwing it.