java求学之路--异常篇

Error 和 Exception

简单分类

  • 检查性异常:是用户错误或问题引起的异常,是程序员无法预见的。如:要打开的文件不存在
  • 运行时异常:是可能被程序员避免的异常
  • 错误(Error):错误与异常不同,是脱离了程序员控制的问题。如:栈溢出、除0

Error 和 Exception区别:Error通常是灾难性的,当出现错误时,JVM一般会终止进程。Exception通常可以被程序处理,我们应该尽可能去处理这些异常

异常处理机制

  • 抛出异常
throw new ArithmeticException();	//主动抛出,一般用于方法中

//假设这个方法中,处理不了这个异常。在方法上抛出异常。使用该方法时需要捕获异常
public void test()throws ArithmeticException{}
  • 捕获异常
try {
	System.out.println(10/0);
}catch (ArithmeticException e){		//catch参数为想要捕获的异常类型
	System.out.println("程序出现异常" + e);
}catch(Throwable e){				//catch参数的范围应该从小到大,否则异常直接捕获
	System.out.println("程序出现异常" + e);
}finally {
	//finally 可以不需要,主要用于关闭资源类操作
	System.out.println("finally");
}
  • 异常处理关键字:try catch finally throw throws
  • 在IDEA中 通过 Ctrl+Alt+t 快捷使用(快捷键失效时,可尝试退出qq或者 Ctrl+Alt+t+Win键)

自定义异常

public class MyException extends Exception{
    private int detail;

    public MyException(int a) {
        this.detail = a;
    }
    
    //toString:异常打印信息
    @Override
    public String toString() {
        return "MyException{" +
                "detail=" + detail +
                '}';
    }
}
posted @ 2022-02-14 00:22  坏人不会飞  阅读(31)  评论(0编辑  收藏  举报