How to handle an exception if you end up with a try block

If I deliver only finally without a catch block, how the exception will be handled

+3
source share
3 answers

The exception will be passed to the call stack, as if your try block did not exist, except that the code will be executed at the end.

Sample code example

try {

   // an exception may be thrown somewhere in here

}
finally {
   // I will be executed, regardless of an exception thrown or not
}
+3
source

Your exception will not be caught, but the finally block will be called and executed eventually. You can write a quick method as shown below and test it:


public void testFinally(){
        try{
            throw new RuntimeException();

        }finally{
            System.out.println("Finally called!!");
        }
    }

+2
source

catch,

. , , finally.

  • finally "", .
  • finally - "", try. , return, break continue. "".

. , squash , try.

public void proc () {
    try {
        // Throws some exception
    } finally {
        return;
    }
}

Details of operators trywith offers finallyare given in JLS 14.20.2

+2
source

Source: https://habr.com/ru/post/1772241/


All Articles