- 基本结构try{要检测的代码块}chatch(异常对象){对应的操作}finally
- throw和throws的区别:
- throw主动抛出异常一般使用在方法内,程序员提前判断,无论是否执行了产生异常的操作,都会抛出异常,如下所示,即使在方法内并没有执行/0操作,但是依旧主动抛出了以长
public class Test {
public static void main(String[] args) {
new Test().text(1, 0);
}
public void text(int a, int b){
if(b == 0){
throw new ArithmeticException();
}
}
}
- 如果方法中不能处理异常,可以向上抛出,使用throws,在调用这个方法的语句中需要使用trychatch语句捕获该异常
public class Test {
public static void main(String[] args) {
try {
new Test().text(1, 0);
} catch (ArithmeticException e) {
throw new RuntimeException(e);
} finally {
}
}
public void text(int a, int b) throws ArithmeticException{
if(b == 0){
throw new ArithmeticException();
}
}
}
- 在多重catch块后面,可以加一个catch(Exception)来处理可能遗漏的异常
- 尽量在finally块里面去释放占用的资源
- IDEA里面使用Alt + Ctrl + t自动增加trycatchfinally语句