C# Exception Handling

Handling an exception means, handling a problem occurred during the program execution. Exceptions is used to transfer program control from one part to another. Exception handling in C#, is built-upon the following four keywords:

  • try - a try block in C#, used to identify a block of code for which a particular exceptions is activated. It is followed by one/more catch block(s)
  • catch - a program catches an exceptions (occurred during the program execution) with an exception handler at the place in a program where you want to handle the problem.
  • throw - a program throws an exception when the problem occurred, using the keyword throw
  • finally - this block is used to execute a given set of statement(s), whether an exception is thrown or not.

Here is the general form to use try, catch, and finally block in C#:

try
{
	// statements causing an exception
}
catch(ExceptionName en1)
{
	// code to handle error
}
catch(ExceptionName en2)
{
	// code to handle error
}
catch(ExceptionName en3)
{
	// code to handle error 
}
finally
{
	// statement(s) to be executed
}

C# Exception Handling Example

Here is an example program, tells how to handle exception in C# program:

/* C# Exception Handling - Example Program */
		
using System;
namespace ExceptionHandlingExample
{
   class NumberDivision
   {
      int res;
      NumberDivision()
      {
         res = 0;
      }
      public void division(int num1, int num2)
      {
         try
         {
            res = num1 / num2;
         }
         catch (DivideByZeroException e)
         {
            Console.WriteLine("Exception caught: {0}", e);
         }
         finally
         {
            Console.WriteLine("Result = {0}", res);
         }
      }
      static void Main(string[] args)
      {
         NumberDivision d = new NumberDivision();
         d.division(25, 0);
         Console.ReadKey();
      }
   }
}

When we compile and run the above program, it will produce the following output:

Exception caught: System.DivideByZeroException: Attempted to divide by zero. 
at ...
Result = 0

C# Online Test


« Previous Tutorial Next Tutorial »

Like/Share Us on Facebook 😋