The use of try-catch-finally in C# (super detailed!)

Overview:

try-catch is an error reporting mechanism that catches exceptions in C#. The following editor will show you the specific principles of try-catch.

grammar:

try
{
    //有可能出现错误的代码写在这里
}
catch
{
    //出错后报出异常
}
finally
{
    //不管什么情况都会执行,包括try-catch里面用了return,可以理解为只要执行了try或者catch,就一定会执行finally
}

understanding:

If there is no error in the code in the try, the program will run the content in the try normally, and the content in the catch will not be executed

If there is an error in the code in the try, the program immediately jumps into the catch to execute the code and throws an exception. At this time, all the codes after the error code in the try will no longer be executed.

Finally, there can be no or only one. If there is finally, no matter whether an exception occurs, it will always run at the end of the error reporting mechanism. Here you can fill in such as: close the database, close the form, etc.

Note: If there is no catch statement block, then finally must exist. If you don't want to handle exceptions here, and submit them to the upper layer for processing when an exception occurs, but no matter whether an exception occurs in this place, you must perform some operations, you can use try-finally, such as: database operations.

Several ways to write catch:

catch: catch any exceptions that occur.

catch(Exception e): will catch any exception that occurs. In addition, the e parameter is also provided. You can use the e parameter to obtain information about the exception when handling the exception.

catch (derived class of Exception e): will catch the exception defined by the derived class, for example, Android Chinese network, I want to catch an invalid operation exception, you can write as follows:

catch(InvalidOperationException e) {....}: If the exception thrown in the try block is InvalidOperationException, it will be transferred to the place for execution, and other exceptions will not be processed. 

Note: There can be multiple or none of the catches, and each catch can handle a specific exception.

to sum up:

The advantage of this method is that it can quickly find errors in the program, but generally novices will not use try-catch, because after an error, they only know that it went wrong, and they don’t know why it went wrong, and can’t accurately locate which line of code went wrong. But using try-catch will improve efficiency, so I suggest you use it.

Guess you like

Origin blog.csdn.net/TGB_Tom/article/details/109630976