public class Test { public static void main(String args[]){ try { System.out.println("1:calling the method"); method(); System.out.println("2:After the method call"); } catch (RuntimeException ex) { System.out.println("3:RuntimeException in main"); } catch (Exception ex) { System.out.println("4:Exception in main"); } finally { System.out.println("5:OK! All is done!"); } System.out.println("6:OK! All is done!"); } static void method() throws Exception{ try { String s = "abc"; System.out.println(s.charAt(3)); } finally { System.out.println("7:method return"); } } }
时间: 2024-02-15 20:28:25 浏览: 160
运行以上代码会输出以下结果:
1:calling the method
7:method return
4:Exception in main
5:OK! All is done!
6:OK! All is done!
在方法method()中,由于尝试访问一个不存在的字符,会抛出StringIndexOutOfBoundsException异常。这个异常不是RuntimeException的子类,因此会被抛出并被main方法中的第二个catch块捕获。在finally块中,会输出“7:method return”,然后返回到main方法。在main方法中,第一个try块会输出“2:After the method call”之前,程序执行到第二个catch块并输出“4:Exception in main”。最后,无论是否抛出异常,finally块中的代码总是会被执行,因此会输出“5:OK! All is done!”和“6:OK! All is done!”。
相关问题
public class Test { public static void main(String args[]){ try { System.out.println("1:calling the method"); method(); System.out.println("2:After the method call"); } catch (RuntimeException
e) { System.out.println("3:Exception caught in main method"); } } public static void method() { try { System.out.println("4:Calling the method"); throw new RuntimeException(); } catch (RuntimeException e) { System.out.println("5:Exception caught in method"); throw e; } finally { System.out.println("6:Finally block executed"); } } }
请问,运行以上代码会输出什么结果?
阅读全文