今天原神2.5更新,急得我要命
异常处理机制
抛出异常
捕获异常
异常处理的关键字:
try、catch、finally、throw、throws
package CaptureAndThrow;
public class Test {
public static void main(String[] args) {
int a = 1;
int b = 0;
try{//监控区域
System.out.println(a / b);
}catch(ArithmeticException e){
System.out.println("程序出现异常,变量b不能为0");
}finally{
System.out.println("finally");
}
/*
解释一下
try代码块监控程序有无异常
如果捕获了ArithmeticException异常,则执行catch代码块
finally善后工作,无论如何finally代码块都会执行
try、catch是必要的,finally可以不要
但是对于IO、资源、scanner等,最后是需要用finally关闭的
*/
//可以catch好几个异常
try {
new Test().a();
}catch (StackOverflowError e){
//或者写Throwable,这是最高级别的异常
System.out.println("栈溢出异常");
}catch (Exception e){
System.out.println("catch Error");
}catch (Throwable e){
System.out.println("catch Throwable");
}finally {
System.out.println("finally");
}
}
public void a(){b();}
public void b(){a();}
}
catch多个异常时,最大的异常Throwable写在最下面
快捷键
对于可能产生异常的代码,Ctrl + Alt + T,会自动生成异常处理机制
package CaptureAndThrow;
public class Demo_1 {
public static void main(String[] args) {
int a = 1;
int b = 0;
try {
System.out.println(a / b);
} catch (Exception e) {
e.printStackTrace();//打印错误的栈信息
} finally {
}
}
}
可以主动抛出异常,一般用于方法中
package CaptureAndThrow;
public class Demo_1 {
public static void main(String[] args) {
int a = 1;
int b = 0;
new Demo_1().test(a,b);
}
public void test(int a, int b){
if(b == 0)
throw new ArithmeticException();
System.out.println(a / b);
}
}
运行结果:
自定义异常
图源B站狂神
自定义异常:
package CustomException;
//自定义的异常类
public class MyException extends Exception{
//传递数字。如果数字>10就抛出异常
private int detail;
public MyException(int a){
this.detail = a;
}
//然后再写toString方法
@Override
public String toString(){
return "MyException{" + detail + '}';
}
}
测试类:
写测试类时会遇到以下情况
有两种解决方式:
红色箭头是把异常抛到方法中去
蓝色箭头是捕获异常
运行结果:
JavaSE完结撒花!!!!
接下来考虑学习JavaEE、GUI、多线程和网络编程,从1月19日到2月16日一共28天,我写了23篇博客,xdm我坚持下来了