Exception Handling
Exception Handling
Exception Handling in C# is a mechanism of handling runtime errors. Exception handling ensures that the program should not halt during the execution. Exception handling does the job of maintaining the flow of the program when some errors occurs. Exceptions that can occur could be anything like logical exception, System Exception etc. The Programmer has to provide some mechanism to handle the exceptions that occur during execution of program to avoid termination of the program.
In C# , the Exception Handling is done with the help of three keywords. TRY,CATCH, and FINALLY. Let's have a look at Syntax.
Syntax
try
{
//code causing exception.
}
catch(Exception ex)
{
//code to handle exception.
}
finally
{
//code which executes irrespective of exception occurs or not.
}
{
//code causing exception.
}
catch(Exception ex)
{
//code to handle exception.
}
finally
{
//code which executes irrespective of exception occurs or not.
}
The try block contains the code which can cause Exception to occur. The catch block catches the respective Exception and the Exception is given particular treatment according to code inside catch block. And the finally block contains the code that must execute even if the Exception is occurred or not.
Exception Classes
Following are the Exception classes in C#.
using System;
namespace exception
{
class Program
{
static void Main(string[] args)
{
int a = 0;
int b = 1;
int c;
try
{
c = b / a;
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Exception raised " +ex.Message.ToString());
Console.ReadKey();
}
}
}
}
namespace exception
{
class Program
{
static void Main(string[] args)
{
int a = 0;
int b = 1;
int c;
try
{
c = b / a;
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Exception raised " +ex.Message.ToString());
Console.ReadKey();
}
}
}
}
Output
Exception raised Attempted to divide by Zero
Exception Handling
Reviewed by LanguageExpert
on
August 21, 2017
Rating:
No comments