During application development, you must check possible errors in the Code and handle them correctly. Ideally, each line of code in the application is executed as expected, each type of resource is always usable. However, in actual development, writing code may inevitably lead to errors, or the network is interrupted or the data service stops running.
The. NET Framework provides a structured exception handling mechanism to handle various errors in the code, that is, try catch.
Here is a small example.
Object OBJ; datetime DT; try {OBJ = new object (); dt = (datetime) OBJ;} catch (invalidcastexception e) // An error occurred while converting invalid Types {console. writeline (E. message);} catch (invalidoperationexception e) // invalid operation exception {console. writeline (E. message);} catch // other exceptions {console. writeline ("program running error! ");} Finally // code block that must be executed {dt = convert. todatetime (" 1900-01-01 "); console. writeline (Dt. tostring ());}
In the preceding example, an invalid type conversion exception is thrown when the object type is converted to the datetime type.
. The structured exception handling principle used in. NET is that structured exception handling code must be added to all possible errors, because this ensures that all resources are correctly released when errors occur, however, you cannot use it blindly, rather than adding try catch to every sentence of code. Because an exception is a resource-consuming mechanism, every time an exception is thrown, the stack of the exception is created and the exception information is loaded, which puts some burden on the program. Therefore, what can be added is not blindly added.
The above code can be simplified to be replaced by is or.
Object OBJ; datetime DT; OBJ = new object (); If (obj is datetime) {dt = (datetime) OBJ;} else {console. writeline ("type conversion is invalid! ");}
This seems to be much simpler, handling exceptions, and saving resources.
Are all exceptions captured using the try catch statement?