默认执行try中内容, 如果try中没有异常抛出,则执行finally内容,最后则会执行 方法尾部内容。
public void test(){
try {
System.out.println("try");
return;
} catch(Exception e){
System.out.println("catch");
}finally {
System.out.println("finally");
}
System.out.println("out");
}
输出内容为try-finally-out.
如果try中抛出了异常 ,但catch中没有设定catch或者设定的捕获异常与抛出的异常不同从而无法捕获到,则执行顺序为 try到触发异常位置,然后进入finlly,此时不会执行out的内容;
public void test() {
try {
int num1 = 2; int num2 = 0;
int result = num1 / num2;
//System.out.println(result);
//throw new NumberFormatException( );
} catch (ArrayIndexOutOfBoundsException e) {
System.out.print("1");
} catch (NumberFormatException e) {
System.out.print("2");
} finally {
System.out.print("4");
}
System.out.print("5");
}
输出为4
发出的异常被捕获到,则执行顺序为,try-》触发异常未知,catch捕获异常,finally代码块,方法尾部代码块
public void test() {
try {
int num1 = 2; int num2 = 0;
//int result = num1 / num2;
//System.out.println(result);
throw new NumberFormatException( );
} catch (ArrayIndexOutOfBoundsException e) {
System.out.print("1");
} catch (NumberFormatException e) {
System.out.print("2");
} finally {
System.out.print("4");
}
System.out.print("5");
}
输出结果为245
throw 是抛出异常,用在代码块中(一般在try块中用来被catch捕获) 如 throw new Exception();
throws 是将异常处理交给上一级处理,用在函数后面,如 public void test() throws Excetion;