Exception Handling in C# is an integrated mechanism within the .NET framework to detect and manage runtime errors. C# provides 3 keywords: try, catch, and finally. For a detailed understanding of Exception Handling in C#, readers can refer to the following article by Mytour.
Exception Handling (Exception Handling) in C#
1. Exception Handling in C#.
2. Uncaught Exception.
3. Catch Block in C#.
4. Handling all exceptions in C#.
5. Throwing an exception.
6. Rethrowing an exception.
7. Standard Exceptions in C#.
8. User-defined Exceptions.
1. Exception Handling in C#
As mentioned by Mytour earlier, exception handling is an integrated mechanism within the .NET framework to detect and handle runtime errors. The .NET framework contains numerous standard exceptions.
Exceptions are anomalies that occur during program execution, they can be user errors, logical errors, or system errors. If users (programmers) do not provide mechanisms to handle these anomalies, the .NET runtime environment will provide default mechanisms to terminate program execution.
C# offers 3 keywords, including try, catch, and finally for exception handling. Among them, the try keyword contains statements that may throw an exception, catch handles an exception if it exists, and finally is used to perform any cleanup operations.
Below is the general structure of try - catch - finally keywords in C#:
If any exception occurs within the try block, control will transfer to the catch block and then to the finally block.
However, in C#, both catch and finally blocks are optional. The try block may have one or more catch blocks or finally blocks, or it may have both catch and finally blocks.
If no exception occurs within the try block, control will directly transfer to the finally block. The statements inside the finally block are always executed. Note that errors may occur when control exits the finally block using break, continue, return, or goto.
In C#, exceptions are objects of type Exception. Exception serves as the base for any exceptions in C#.
C# provides some standard exceptions; however, if users want to create their own exception classes, they can do so as long as these exception classes inherit from the Exception class or one of the standard derived classes of the Exception class, such as DivideByZeroExcpetion or ArgumentException, ... .
2. Uncaught Exception
The following program compiles but will display an error during execution. Dividing by 0 is abnormal, and the program will terminate with an error message.
Any uncaught exception within the current context propagates to higher contexts, seeking a matching catch block to handle it. If no matching catch block is found, the default mechanism of the .NET runtime will terminate the entire program execution.
The program, after modification with exception handling mechanisms, looks as follows. Here, we utilize an object of the standard exception class DivideByZeroException to handle the divide by zero exception.
The result returned from the above code snippet appears as follows:
In the example above, the program doesn't terminate; instead, control shifts from the point of exception occurrence inside the try block to the catch block. If any matching catch block is found, the execution continues within that catch block. If a finally block is present, the code inside the finally block will be executed before completion.
A small note is that in C#, the catch block is optional. The following program is a valid one in C#:
However, in this case, since there's no exception handling in the catch block, the execution will terminate. Before termination, the program statements inside the finally block will be executed. In C#, the try block must be followed by either a catch block or a finally block.
3. Catch Block in C#
A try block can throw multiple exceptions that we can handle by using multiple catch blocks. A point to note is that a specific catch block should precede a general catch block; otherwise, the compiler will display a compilation error.
4. Handling All Exceptions in C#
By providing a catch block without square brackets or parameters, we can catch all exceptions occurring within the try block.
Alternatively, we can use a catch block with a parameter of type Exception to catch all exceptions occurring within the try block, because in C#, all exceptions are directly or indirectly inherited from the Exception class.
The following program illustrates how to handle all exceptions with the Exception object.
5. Throwing an Exception
C# can throw an exception within a program. To throw an exception in C#, we use the keyword 'throw'. The syntax for throwing an exception in C# is as follows:
throw exception_obj;
For instance, the following commands throw an ArgumentException:
6. Re-throwing an Exception
Exceptions caught within a catch block can be re-thrown to a higher context using the throw keyword inside the catch block.
The program below illustrates how to re-throw an exception in C#:
7. Standard Exceptions in C#
In C#, there are two types of exceptions: those created by the executing program and those created by the common language runtime.
System.Exception is the base class for all exceptions in C#. Some exception classes that inherit from System.Exception include ApplicationException and SystemException. These two classes serve as the base for most other runtime exceptions. Other exceptions inheriting from System.Exception include IOException, WebException, and so on.
Runtime throws SystemException. ApplicationException is thrown more by user programs rather than runtime. SystemException includes ExecutionEngineException, StackOverFlowException, and so forth.
8. User-Defined Exceptions
In C#, it's possible to create custom exception classes, but Exception must be the ultimate base class for all exception classes in C#. Therefore, user-defined exception classes must inherit from the Exception class or one of its standard derivative classes.
So the article above has just introduced you to exception handling in C#. If an exception is defined within the System namespace to describe exceptional conditions, it will have significance with the class. Finally, if code catches an exception but doesn't handle it, you may consider whether to wrap that exception with additional information before rethrowing it. To learn more about C#, check out what File I/O in C# is all about.
