try-catch-finally
作用
主要是用来捕获一些程序中的异常,例如 NullPointerException、IndexOutOfBoundsException、ArithmeticException等。
try {
int i = 10 / 0; // throw a ArithmeticException!
} catch (ArithmeticException e) {
// do something
}
触发机制
1、catch 代码块只有在 try 代码块中抛出相应的异常,或者其异常子类时才会执行。
try {
int i = 10 / 0; // throw a ArithmeticException!
} catch (NullPointerException e) {
System.out.println("NullPointerException");
} catch (ArithmeticException e) {
System.out.println("ArithmeticException");
} catch (Exception e) {
System.out.println("Exception");
}
执行结果
2、finally 代码块一定会被执行,不管 try 代码块是否出现异常。
try {
int i = 10 / 0; // throw a ArithmeticException!
} catch (NullPointerException e) {
System.out.println("NullPointerException");
} catch (ArithmeticException e) {
System.out.println("ArithmeticException");
} catch (Exception e) {
System.out.println("Exception");
} finally {
System.out.println("finally");
}
执行结果
注意点
1、try 代码块不可单独存在,必须搭配 catch 代码块或 finally 代码块。
try {
int i = 10 / 0;
} finally {}
try {
int i = 10 / 0;
} catch (Exception e) {}
2、笔试题
public class CSDNTest {
public static void main(String[] args) {
System.out.println(method());
}
private static int method() {
int result;
try {
result = 1;
int i = 10 / 0;
} catch (Exception e) {
result = 2;
} finally {
result = 3;
}
return result;
}
}
最后执行结果
如果是以下这段代码呢?
public class CSDNTest {
public static void main(String[] args) {
System.out.println(method());
}
private static int method() {
int result;
try {
result = 1;
return result;
} catch (Exception e) {
result = 2;
} finally {
result = 3;
}
return result;
}
}
执行结果
JVM 在执行 finally 代码块之前,会将 try-catch 代码块的结果集先暂存起来。
额外
finally 代码块一般是用来释放一些资源的。不过 java7 之后,就引入了 try-with-resources 语法。它可以自动地在语句块执行完后关闭资源。使用这种语法可以避免在 finally 块中显式地关闭资源,从而减少代码的复杂性。