15.异常机制
异常处理机制
捕获异常
关键字:try、catch、finally
- finally:无论是否捕获到异常,这段代码最终都会执行。非必须,可以不写,可以用来释放资源
- catch:参数为想要捕获的异常类型,最高异常:Throwable。一个try可以跟多个catch语句,写多个时,异常要从小到大写
public class Application {
public static void main(String[] args) {
int a = 1;
int b = 0;
try {
System.out.println(a / b);
}catch (ArithmeticException e){ // 想要捕获的异常类型,最高:Throwable
e.printStackTrace(); // 打印错误的栈信息
System.out.println("被除数不能为0");
}finally {
System.out.println("结束");
}
}
}
抛出异常
关键字:throw、throws
- throws 标识该方法可能会抛出异常,并不一定会发生。如果出现这个异常需要方法上层的调用方去解决
- throw一定会抛出某个异常
- throw出现在方法体内,throws出现在方法头
public class Application {
public static void main(String[] args) {
int a = 1;
int b = 0;
try {
if (b==0){
throw new ArithmeticException();
}
} catch (ArithmeticException e) {
System.out.println("运行异常");
}
}
}
public class Application {
public static void main(String[] args) {
try {
new Application().test(1, 0);
} catch (ArithmeticException e) {
e.printStackTrace();
System.out.println("11");
}
}
public void test(int a, int b) throws ArithmeticException{
if (b==0){
throw new ArithmeticException();
}
System.out.println(a/b);
}
}
自定义异常
public class Application {
public static void main(String[] args) {
try{
throw new MyExcept(10);
}catch (MyExcept e){
System.out.println("错误"+e);
}
}
}
// 自定义一个异常类,继承Exception
class MyExcept extends Exception{
private int d;
public MyExcept(int a){
this.d = a;
}
public String toString(){
return ("异常:"+d);
}
}

浙公网安备 33010602011771号