In this example, a method tests for a division by zero, and catches the error. Without the exception handling, this program would terminate with a DivideByZeroException was unhandled error.
int SafeDivision(int x, int y)
{
try
{
return (x / y);
}
catch (System.DivideByZeroException dbz)
{
System.Console.WriteLine("Division by zero attempted!");
return 0;
}
}
Exceptions have the following properties:
- When your application encounters an exceptional circumstance, such as a division by zero or low memory warning, an exception is generated.
- Use a try block around the statements that might throw exceptions.
- Once an exception occurs within the try block, the flow of control immediately jumps to an associated exception handler, if one is present.
- If no exception handler for a given exception is present, the program stops executing with an error message.
- If a catch block defines an exception variable, you can use it to get more information on the type of exception that occurred.
- Actions that may result in an exception are executed with the try keyword.
- An exception handler is a block of code that is executed when an exception occurs. In C#, the catch keyword is used to define an exception handler.
- Exceptions can be explicitly generated by a program using the throw keyword.
- Exception objects contain detailed information about the error, including the state of the call stack and a text description of the error.
- Code in a finally block is executed even if an exception is thrown, thus allowing a program to release resources.