Day25捕获与抛出异常
异常处理中的五个关键词
try,catch,finally,throw,throws
package com.exception;
public class Test {
public static void main(String[] args) {
int a = 1;
int b = 0;
//System.out.println(a/b);//存在逻辑错误,0不能作为被除数,主动抛出这个异常
//运用try,catch语句去捕获处理这个异常
//若要捕获多个异常,要从大到小,否则会报错,因为范围小的会被覆盖
try{//try作为一个监控区域
new Test().a();
}catch (Error e){//捕获异常
System.out.println("Error");
}catch (Exception e){
System.out.println("Exception");
}catch (Throwable e){
System.out.println("Throwable");
}
finally{//处理善后工作,无论实际有没有异常,都会执行finally,但非必要
System.out.println("finally");
}
}
//运行时会造成错误,此时上面的try,catch就会捕获错误,但实际运用中不建议捕获错误
//因为错误的特性决定了其强行运行下去无太大意义,还可能导致其他问题
public void a(){
b();
}
public void b(){
a();
}
}
package com.exception;
public class Test2 {
public static void main(String[] args) {
int a = 1;
int b = 0;
//快捷键 ctrl+alt+t
try {
System.out.println(a/b);
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
}
package com.exception;
//throw与throws
public class Test3 {
public static void main(String[] args) {
try {
new Test3().test(12,0);
} catch (ArithmeticException e) {
e.printStackTrace();
} finally {
System.out.println("finally");
}
}
//假设在方法中无法处理这个异常,则在方法上抛出异常
public void test(int a,int b) throws ArithmeticException{
if(b==0){
throw new ArithmeticException();//主动抛出异常,在方法中使用
}
System.out.println(a/b);
}
}