codescracker


c#

C# Exception Handling



« Previous Tutorial Next Tutorial »


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:

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

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test