异常处理五个关键字
try、catch、finally、throw、throws
package 异常;
public class Demo01 {
public static void main(String[] args) {
int a = 1;
int b = 0;
try { //try监控区域
System.out.println(a/b);
}catch (ArithmeticException e){ //catch捕获异常,括号内的内容是想要捕获的异常类型
System.out.println("程序出现异常");
}catch (Error e){
System.out.println("Error");
}
catch (Exception e){
System.out.println("Exception");
}
catch (Throwable e){
System.out.println("Throwable");
} //可以捕获多个异常,但是级别需要从小到大
finally { //finally处理善后工作,finally一些情况下可以不要,但try..catch需要
System.out.println("finally");
}
//快捷键 ctrl+alt+T可以自动生成相应的代码块
}
}
输出结果:
程序出现异常
finally
主动抛出异常
throw
package 异常;
public class Demo01 {
public static void main(String[] args) {
int a = 1;
int b = 0;
try {
if(b==0){ //明确知道某种情况下会出错的话,可以使用throw主动抛出异常
throw new ArithmeticException();
}
System.out.println(a/b);
}
catch (Exception e){
System.out.println("Exception");
}
}
}
throws
package 异常;
public class Demo01 {
public static void main(String[] args) {
int a = 1;
int b = 0;
new Demo01().test(a,b);
}
public void test(int x,int y) throws ArithmeticException{//假设这个方法解决不了异常,可以在方法上抛出异常
if(y==0){
throw new ArithmeticException();
}
System.out.println(x/y);
}
}