![]() |
VOOZH | about |
In C#, exception handling is the process of responding to runtime anomalies, called exceptions, in a controlled way. Proper handling ensures that a program continues to run or exits gracefully instead of crashing unexpectedly. C# provides structured exception handling using the keywords try, catch, finally, and throw.
try{
// Code that may throw an exception
}catch (ExceptionType ex){
// Code to handle the exception
}finally{
// Code that will always execute
}
The try block contains the code that might throw an exception. Only the code inside the try block is monitored for exceptions.
Division by zero detected.
Explanation:
The catch block handles exceptions thrown in the try block. You can have multiple catch blocks to handle different exception types.
Output
Cannot divide by zero.
Explanation:
The finally block is mainly used for cleanup tasks such as closing files, releasing unmanaged resources, or freeing external connections.
Output
Cannot divide by zero.
Execution completed.
Explanation:
The throw keyword is used to manually raise an exception. It can be used to signal that an error or invalid condition has occurred.
Explanation:
Output:
Error: Division by zero is not allowed.
Execution of try-catch block finished.
Explanation:
C# allows multiple catch blocks to handle different types of exceptions:
Output:
Array index is out of range.