Java exception handling throws, throw, try...catch..finally

There are many exceptions in Java, and this exception mechanism can help handle unknown errors in the program. Regarding exception handling, there are try catch block, throw, throws

1.throws

      Handling exceptions in the throws method is also called declaring exceptions, which identifies the problem and reports it to the caller. If a compile-time exception is thrown through throw in the method, but it is not caught and processed, it must be declared through throws and let the caller handle it. The keyword throws is used on the method declaration to indicate that the current method does not handle exceptions, but reminds the caller of the method to handle exceptions (throwing exceptions).

      throws is used to declare the exception class . If the method may have multiple exceptions, then multiple exception classes can be written after throws, separated by commas.

1.1 Statement format

    Modifier return value type method name () throws exception class name {}

1.2 Code

private void syncData(ProductBaseVo vo) throws JsonProcessingException {
        if (null != vo) {
            rabbitController.syncDataChange(JsonUtils.toJsonString(vo).getBytes(), RabbitConstants.FAN_EXCHANGE, null);
        }
    }

2.throw

    When writing a program, we must consider the situation where the program has problems. For example, when defining a method, the method needs to receive parameters. Then, when the calling method uses the received parameters, it is first necessary to make a legal judgment on the parameter data. If the data is not legal, it should tell the caller to pass legal data in. At this time, an exception needs to be thrown to tell the caller. In java, a throw keyword is provided, which is used to throw a specified exception object.

   throw is used in a method to throw an exception object, pass the exception object to the caller, and end the execution of the current method.

2.1 Statement format

modifier return value type method name (parameter list) [throws exception type] {

    if (judgment condition) {

       throw new ExceptionObject("The cause of the exception");

      }

}

2.2 code

public Boolean updateActivate(ProductDeviceBo bo) { 
    if (null == bo) { 
        throw new RuntimeException("Device activation failed: deviceVo is null"); 
    } 
    if (org.apache.commons.lang3.StringUtils.isBlank(bo.getId( ))) { 
        throw new RuntimeException("Device activation failed: the device id is null"); } 
    if 
    (null == bo.getActivateTime()) { 
        throw new RuntimeException("Device activation failed: the activation time is null"); 
    } 
    log.info("Device activation->device id=" + bo.getId() + "; activation time->" + bo.getActivateTime()); // 
    Determine whether the id exists in the database 
    ProductDeviceVo vo = baseMapper.selectDeviceInfoById (bo.getId()); 
    if (null == vo) { 
        throw new RuntimeException("The device does not exist"); 
    }
    return baseMapper.updateActivate(bo.getId(), bo.getActivateTime()) > 0;

}

3. try catch

try-catch is used to catch the exception of the code segment and handle it

The try-catch code block is divided into two blocks, the first block is try{}, and the second block is catch (reference of exception) {}.

try-catch is generally placed outside the loop.

try-catch, try is to try, try to see if you can go through the entire scope normally , and throw an exception if you can't. Therefore, a program segment that may throw an exception is often placed in the try block. And catch is to handle the exception thrown in try, where the parameter list of catch receives an exception reference, which is the reference of the exception thrown by throw.
try-catch can be nested, the following is an example of try-catch nesting:

---------------------------------------------- First form -------------------------------------------------- -

try{ 
     System.out.println("********************** SUCCESS****************** ****"); 
}catch (Exception e){ 
    System.out.println("**********************Failed****** *****************"); 
    e.printStackTrace(); 
}

-----------------------------------------------Second Form-- -------------------------------------------------- ----------

try{

   System.out.println("********************** SUCCESS******************** **");

}catch (Exception e){

 System.out.println("**********************Failed******************** **");

  e.printStackTrace();

}finally {

   System.out.println("**********************inner finally****************** ****");

}

---------------------------------------Third Form---------- -----------------------------------------------

try{

   System.out.println("********************** SUCCESS******************** **");

}finally {

   System.out.println("**********************inner finally****************** ****");

}

4. The difference and connection between try-catch, throw, throws

the difference

1. Throw represents an action, which means an action that throws an exception; throws represents a state, which means that a method may throw an exception.
2. throw is used in method implementation, and throws is used in method declaration.
3. Throw can only be used to throw one kind of exception, while throws can throw multiple exceptions.

4. Throw can be used with the try-catch-finally statement block or with throws.

5. Throws are generally used alone, and then caught by the exception handling method.

connect

try .... catch is to use catch to catch the exception that may occur in a certain operation in try and handle it.

throw does not handle the exception, but directly throws the exception. Throw new Exception () is to throw an Exception, which is handled by other methods.

So: try....catch is for catching Exception, and throw is for throwing Exception for others to catch.

If throws is used in a method, then this method will throw an exception upwards, then when calling this method, you must put this call in a try...catch block to handle this exception.

There are two ways to handle exceptions

1. Declare an exception, that is, add throws ExceptionName,... after the method name, the method itself just throws an exception, and the caller of the function catches the exception. If an exception occurs, the exception will find a matching processing method along the call stack. If it reaches the bottom of the call stack and still does not find it, an exception will be output and the program will be terminated.

2. Catch exceptions. Through the try catch method, the exception handling statement is placed in the catch clause.

Contact two:

For the program block that may have an exception thrown, wrap it with try{}, and then use catch to catch the exception, and handle the exception in the catch. If there is an exception in the try, the program will go to the catch instead of interruption.

Try and catch can only get the exceptions raised when the program is running, while the throw statement can cause a clear exception. The program will stop immediately after reaching the throw statement, and will not execute the subsequent programs.

Guess you like

Origin blog.csdn.net/zw899004/article/details/130363389