异常处理
抛出异常
捕获异常
异常处理的五个关键字:try、catch、finally、throw、throws
在方法体中的异常,要么在方法体中捕获,要么向上抛出。向上抛出的意思是需要在调用该方法时候使用try,catch进行捕获。
存在一些潜在异常的时候,会提示波浪线,则摁住alt+enter会提示应该怎么处理。
package exception;
public class demo {
public static void main(String[] args) {
int a=1;
int b=0;
//假设要捕获多个异常的时候,需要从范围小的到范围大的去写。
try {//try监控区域
System.out.println(a/b);
}catch (Exception e){//catch用于捕获异常
System.out.println("a/b出现了错误!");
}catch (Error error){
System.out.println("程序出现了error");
}catch (Throwable throwable){
System.out.println("throwable");
}finally {//处理善后工作
System.out.println("我一定会执行!");
}
//finally可要可不要
//快捷键:选中被监控区域,然后ctrl+alt+t
try {
System.out.println(a/b);
} catch (Exception e) {
e.printStackTrace();
} finally {
}
if (b==0){//throw throws
throw new ArithmeticException();//主动抛出异常。
}
}
}

浙公网安备 33010602011771号