Exception handling (try catch finally)

introduce        

        Sometimes, we know that errors may occur, but we cannot be 100% sure that they will not occur. At this time, it is better to anticipate errors and write code that is robust enough to handle them without interrupting program execution.

        Exceptions are errors that occur in code during runtime.

Example:     

int[] myArray = {1,2,3,4};   

int myEle = myArray[4];//array subscript out of bounds

When running here, an exception will occur, and the definition of this exception has been defined in the CLR. If we don't handle this exception, then when the exception occurs, the program will terminate, and then the code behind the exception cannot be executed.

exception handling

structure

Our grammatical structure for handling exceptions is as follows (contains three keywords try catch finally)     

try{      

   ...     

}     

catch( <exceptionType> e ){         

...  

   }     

finally{     

}

Among them, the catch block can have 0 or more, and finally can have 0 or 1. But if there is no catch block, there must be a finally block. If there is no finally block, there must be a catch block. The catch block and finally block can exist at the same time.

The role of code blocks

The try block contains code (one or more statements) that may throw exceptions

The catch block is used to catch exceptions. When an exception occurs in the code, the catch block will be executed if the exception type is the same as the type in the catch block. If the parameter of the catch block is not written, it means that the catch block will be executed when any exception occurs.

The finally block contains code that will always be executed, regardless of whether an exception occurs

Guess you like

Origin blog.csdn.net/qq_52397831/article/details/126926507