异常抛出和捕获
-
抛出异常
-
异常处理的五个关键字
try,catch,finally,throw,throws
package exception;
public class test {
public static void main(String[] args) {
int a=0;
int b=1;
//假设要捕获多个异常要从小到大的写
try {//try监控区域
if (a==0){
throw new ArithmeticException();
}
System.out.println(b/a);
}catch (Exception e){//catch捕获异常
System.out.println("格式错误");
}catch (Throwable e){
System.out.println("严重错误");
}
finally {//处理善后工作
System.out.println(123);
//finally 可以不要finally,假设io资源关闭
}
}
public void a(){
b();
}
public void b(){
a();
}
}
package exception;
public class test3 {
public static void main(String[] args) {
new test3().add(1,0);
}
public void add(int a , int b)throws ArithmeticException{
if (b==0){
throw new ArithmeticException();
}
System.out.println(a/b);
}
}
package 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();
}
}
}

浙公网安备 33010602011771号