Today when reading the Code book, useful to Try--catch--finally, and then checked the specific attention and application.
In simple terms:
try {
There may be code or code snippets that are wrong
}
catch{
If the code in the try is wrong, an error is obtained here
}
finally{
There can be no, or only one.
In order to ensure the stability of the program, the enforcement of a piece of the program;
Regardless of whether the code has errors/exceptions, this is the last step in handling the exception structure
There is one exception: if there is no catch statement block, then the finally block is required.
}
A try must be followed by a catch, not with a compile, finally is a mandatory patch, such as forcing the database connection to be closed and destroying the database object
1. The code that anticipates the possibility of throwing an exception is included in the TRY statement block.
2. If an exception occurs, the execution of the catch is transferred. Catch is written in several ways:
Catch
This will catch any exceptions that occur.
catch (Exception e)
This will catch any exceptions that occur. In addition, the E parameter is provided, and you can use the e parameter to obtain information about the exception when handling the exception.
catch (derived class E of exception)
This captures the exceptions defined by the derived class, for example, I want to catch an exception for an invalid operation, which can be written as follows:
catch (InvalidOperationException e)
{
....
}
This way, if the exception thrown in the Try statement block is InvalidOperationException, it will go to that place and the other exception is not handled.
. NET finds exception handling blocks in the order in which you catch them, and if found, handles them and throws them up one level if they are not found. If there is no previous level, then thrown to the user, at this point, if you are debugging, the program will break run, if the program is deployed, will be aborted.
If there is no catch block, the exception is always thrown to the upper (if any), or the program is interrupted.
3. Finally
Even if you return with return within a try block, finally is always executed before returning.
If you do not want to handle the exception here, and when the exception occurs, commit to the upper layer processing, but in this place no matter what happens, you have to do something, you can use try Finally,
Return can be placed in a try statement block. But no matter when the time comes to return, the finally will be executed before returning.
Finally, it is best not to have return in case the program mentions the exit, the return value is not the value saved in the try or catch.
Summary: Try--catch--finally,that's all.
C # Try Catch finally simple introduction and application