Does a finally block always get executed in Java?

前端 未结 30 1584
逝去的感伤
逝去的感伤 2020-11-21 07:24

Considering this code, can I be absolutely sure that the finally block always executes, no matter what something() is?

try         


        
30条回答
  •  时光说笑
    2020-11-21 07:35

    No, not always one exception case is// System.exit(0); before the finally block prevents finally to be executed.

      class A {
        public static void main(String args[]){
            DataInputStream cin = new DataInputStream(System.in);
            try{
                int i=Integer.parseInt(cin.readLine());
            }catch(ArithmeticException e){
            }catch(Exception e){
               System.exit(0);//Program terminates before executing finally block
            }finally{
                System.out.println("Won't be executed");
                System.out.println("No error");
            }
        }
    }
    

提交回复
热议问题