Explain how to Throw and Catch Exceptions in C#.NET.
- Exceptions or errors are unusual occurrences that happen within the logic of an application.
- The CLR provides structured way to deal with exceptions using Try/Catch block.
- It provides a way to transfer control from one part of a program to another.
Catch:- It catches an exception with an exception handler at the place in a program where you want to handle the problem.
- It indicates the catching of an exception.
- There are multiple Catch blocks permitted.
Syntax:try
{
//Statements
}
catch(ExceptionName e1)
{
//Error handling code
}
catch(ExceptionName e2)
{
//Error handling code
}
catch(ExceptionName eN)
{
//Error handling code
}
Throw:- It throws an exception when a problem shows up.
- It is done using 'throw' keyword.
- A Throw statement can be used in the catch block to throw the present object as:
Catch(Exaception e)
{
//Statements
Throw e
}
- It is directly or indirectly derived from the System.Exception class.