java八股文笔记-异常

166 阅读3分钟

throw

异常就是当程序执行到一段代码,发生异常后,就new一个对应的类的对象,这个类是一个异常类,如:NullPointerExceptionNumberFormatException,然后throw或者catchthrow就是抛出一个异常,和return对比。

throwreturn
异常退出正常退出
throw后执行的代码不定,看异常处理机制动态决定返回位置确定:上一级调用者

try/catch

System.out.println("请输入一个数字");
try {
  int num = Integer.parseInt(args[0]);
  System.out.println(num);
} catch(NumberFormatException e) {
  System.out.println("参数" + arg[0] + "不是有效数字,请输入数字");
}

如果在try内跑出来异常,可以由catch来捕获,捕获后程序还会继续运行而不会退出,只是try后续的代码不会执行。

异常类体系(记下来)

image.png

Throwable是所有异常类的基类,他有两个子类Error和Exception。

Error表示系统错误或资源耗尽,应用程序不抛出或处理,虚拟机错误及其子类,内存溢出错误和栈溢出错误。Error及子类都是未受检异常。

Exception中有很多子类,也可以继承Exception自定义异常,其中列出来数据库异常,IO异常,和运行时异常(未受检异常)受检异常不能通过编译。

异常说明
NullPointerException空指针异常
IllegalStateException非法状态
ClassCastException非法强制类型转换
IllegalArgumentException参数错误
异常说明
NumberFormatException数字格式错误
IndexOutOfBoundsException索引越界
ArrayIndexOutOfBoundsException数组索引越界
StringIndexOutOfBoundsException字符串索引越界

这些异常大部分只是定义了几个父类的构造函数。

自定义异常

然后自定义异常继承的RuntimeException或他的某个子类,则自定义异常也是未受检异常;如果继承的是Exception和Exception其他子类,则自定义异常是受检异常。

public class AppException extends Exception {
  public AppException {super();}
  public AppException(String message, Throwable cause) {super(message, cause);}
  public AppException(String message) {super(message);}
  public AppException(Throwable cause) {super(cause);}
}

异常处理

异常处理包括catch、throw、finally、try-with-resources和throws

catch匹配

try{
}catch(NumberFormatException e){
}catch(RuntimeException e){
}catch(Exception e){
}

上方异常要是下方异常的子类,java7开始支持一种新语法

try{
} catch (ExceptionA | ExceptionB e) {}

throw和finally

处理完异常之后,可以通过throw抛出异常给上一层,可以是原来的异常,也可以是新异常。

finally内代码,无论有无异常发生都会执行。

  1. 如果没有异常发生,try执行后执行finally

  2. 如果有异常被catch,catch执行后执行finally

  3. 如果有异常发生但没被catch,在异常被抛出前执行finally

注意:如果try或catch中有return时,也会先执行完finally中的代码再去执行return;如果finally内有return或抛出异常,则会覆盖掉catch和try中的return和异常。

try-with-resources

finally一般用于释放资源,java7之前要实现AutoCloseable接口之后,在finally中调用close()方法,代码如

public interface AutoCloseable {
  void close() throws Exception;
}
public static void useResource() throws Exception {
  AutoCloseable r = new FileInputStream("hello");   //创建资源
  try{               //使用资源
  } finally {
    r.close();
  }
}

java7支持了一种新语法,在执行完try语句之后自动执行close()方法。

public static void useResource() throws Exception {
  try (AutoCloseable r = new FileInputStream("hello")){ //创建资源
     //使用资源  
  }
}

throws

throws跟在方法后面,可以声明多个异常,以逗号分隔。表示:这个方法可能会抛出这些异常,且没有处理或者没有处理完,调用者必须进行处理。