The occurrence of an error is not always the reason for writing the application, and sometimes an error occurs because the program is causing an environment where the end user of the application throws or runs the code. In any case, we should anticipate the errors that occur in the application and encode them accordingly. The mechanism for handling errors in C # can provide a custom handling method for each error and separate the code that identifies the error from the code that handles the error.
First, the Exception class
In C #, an exception object is created (or thrown) when a particular exception error condition occurs. This object contains information that helps you track the problem. NET provides a number of predefined exception classes, and we can also create our own exception classes.
Second, catch the exception
In order to handle possible error conditions in C # code, it is common to divide the relevant part of the program into three different types of code blocks:
- The try block contains code that makes up the normal operation of the program, but this part may encounter some serious errors
- The catch quickly contains code that handles various error conditions that are encountered in executing the code in the try block, which can also be used to log errors.
- The finally block contains code that cleans up resources or performs other operations that are typically performed at the end of a try block or catch block. The finally block executes regardless of whether an exception is thrown. Finally blocks are completely optional, and you do not need to include a secondary block if you do not need to clean up the code.
Third, System.Exception properties
There are many other properties in the System.Exception exception class:
Property |
Description |
Data |
This property can add a key/value statement to an exception to provide additional information about the exception |
HelpLink |
Link to a Help file to provide more information about the exception |
InnerException |
If this exception is thrown in a catch block, it contains the exception object that sent the code to the CATCH block |
Message |
Text that describes the error condition |
Source |
The application name or object name that caused the exception |
StackTrace |
The details of the method call on the stack, which helps to keep track of the method that throws the exception |
TargetSite |
Describes the method that throws the exception. NET Reflection Objects |
If you write an executable program, you should capture as many exceptions as possible and handle them in a reasonable manner.
Handling of C # errors and exceptions