Does a finally block run even if you throw a new Exception?

后端 未结 6 912
梦毁少年i
梦毁少年i 2020-12-22 20:42

In this code will someVar be set even if the catch block is executed and the second Exception is thrown?

public void someFunction() throws Excep         


        
6条回答
  •  抹茶落季
    2020-12-22 21:00

    Finally, block always executes.

    public class ExceptionTest {
    
    public static void someFunction(String input) throws Exception {
        try {
            if( input.equals("ABC") ) {
                System.out.println("Matched");
            }
        } catch (Exception e) {
            throw new Exception(e);
        } finally {
            System.out.println("Input Is "+input+" Finally Executed!!!");
        }
    }
    
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {
            System.out.println("********* Test with VALUE ********* ");
            someFunction("ABC");
            System.out.println("\r\n********* Test with NULL  ********* ");
            someFunction(null);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    

    }

提交回复
热议问题