What is Exception Handling? Write a suitable program how to handle exception handling.
Exception Handling
- An exception is a problem that arises during the execution of a program.
- A C# exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero, Array Index Out of Bounds, etc
- Exceptions provide a way to transfer control from one part of a program to another.
- C# exception handling is built upon four keywords: try, catch, finally, and throw.
- try: A try block identifies a block of code for which particular exceptions are activated. It is followed by one or more catch blocks.
- catch: A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception.
- finally: The final block is used to execute a given set of statements, whether an exception is thrown or not thrown.
- throw: A program throws an exception when a problem shows up. This is done using a throw keyword.
Exception Handling Syntax
try
{
// statements causing exception
}
catch( ExceptionName e1)
{
// error handling code
}
catch ExceptionName e2 )
{
// error handling code
}
catch( ExceptionName eN )
{
// error handling code
}
finally
{
// statements to be executed
}
Example of Exception Handling
int a = 10 ;
int b = 0 ; // assign b = 2
int c = a / b;
Console.WriteLine(c);
int[] arr = {(10, 20, 12); Console.WriteLine(arr[5]);
}
catch (DivideByZeroException el)
{
Console.WriteLine(el. ToString());
}
catch (IndexOutOFRange Exception e2)
{
Console.WriteLine("Array index problem");
}
Comments
Post a Comment