The exception handling feature of the C# language helps you handle any unexpected or unusual situations that occur while your program is running. Exception handling uses the try, catch, and finally keywords to try certain operations to handle failures, and although these operations have the potential to fail, you can try to do so if you are sure you need to do this and want to clean up resources afterwards. Common Language Runtime (CLR), . NET Framework or any third-party library or application code can generate exceptions. Exceptions are created using the throw keyword. In many cases, exceptions may not be raised by a method called directly by code, but by another method further down the call stack. In this case, the CLR expands the stack to see if there is a method that contains a catch block for that particular exception type, and if it finds such a method, it executes the first such catch block found. If no appropriate catch block is found anywhere in the call stack, the process is terminated and a message is displayed to the user. In this example, a method is used to detect if there is a situation where it is divided by zero; If there is, the error is caught. If there is no exception handling, this program will terminate and produce a "DivideByZeroException Not Handled" error.- class ExceptionTest
- {
- static double SafeDivision(double x, double y)
- {
- if (y == 0)
- throw new System.DivideByZeroException();
- return x / y;
- }
- static void Main()
- {
- // Input for test purposes. Change the values to see
- // exception handling behavior.
- double a = 98, b = 0;
- double result = 0;
- try
- {
- result = SafeDivision(a, b);
- Console.WriteLine("{0} divided by {1} = {2}", a, b, result);
- }
- catch (DivideByZeroException e)
- {
- Console.WriteLine("Attempted divide by zero.");
- }
- }
- }
Copy code
|