Java_异常

运行时异常

  • 例如数组越界,继承与RuntimeException,在编译期间不是必须要捕获的异常.

public static void main(String[] args) {
    Object[] arr = {1,2,3};
    try {
        Object obj = arr[10];//try中的异常会终止异常之后的代码
        System.out.println("错误之后"); //错误之后不执行这句
    } catch (Exception e) {//捕获到异常之后执行
        //处理错误
        //e.printStackTrace();
        System.out.println("catch块");
    }
    System.out.println("1");
}

 public static void main(String[] args) {
        Object[] arr = {null,null,1};
        //Object value = arr[10];//数组越界
        try {
//          Object obj = arr[10];
//          arr[1].equals(1);
            //其他异常
            
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("数组越界");
        }catch (NullPointerException e) {
            System.out.println("空指针异常");
        }catch (RuntimeException e) {
            System.out.println("其他异常");
        }
       System.out.println("1");
        
    }
public static void main(String[] args) {
      add();
    try {
        
    } catch (Exception e) {
        
    }finally{//不管有没有异常都执行
        //关闭文件
    }
}
  static int add(){
      try {
        int a = 1;
        System.out.println(a);
        return a;
    } catch (Exception e) {
        
    }finally{
        System.out.println("finally");
    }
      return 1;
      
  }
  • 上面是try....catch 还有 try ....catch..catch try...catch...finally
  • 必须在try之后添加catch或finally块.try块后可同时接catch和finally块,但至少有一个块.
  • 必须遵循块顺序:若代码同时使用catch和finally块,则必须将catch块放try块之后.
  • finally是一定会执行的.
  • throw抛出异常的两种情况 1.抛出异常给调用者处理 2.在catch块中捕获到的异常不想处理,抛给调用者处理.
  • throws 1.抛出异常给调用者处理 2.当函数中抛出非运行时异常,需要throws声明一下.

非运行时异常

  • 例如io异常,数据库异常,在程序编译阶段一定要使用try...catch捕获.
  • 非运行异常是RuntimeException以外的异常,类型上都属于Exception类及其子类,如IOException SQLException等以及用户自定义的Exception异常, 对于这种异常,java编译器强制要求我们必须对出现的这些异常进行catch处理,否则程序就不能编译通过.所以 面对这种异常不管我们是否愿意,只能自己去写一堆catch块处理可能的异常.
public static void main(String[] args)  throws Exception{
      //创建一个文件读取对象
      FileReader reader = new FileReader("文件的名字");//必须捕获    非运行时异常
      
//    try {
//        FileReader reader = new FileReader("文件的名字");//必须捕获    非运行时异常
//  } catch (Exception e) {
//      
//  }
      
 }
  //当函数中抛出非运行时异常 需要throws声明一下.如果抛出多个 用,隔开写  或者直接抛出一个共同父类
  void fileNotFound()throws FileNotFoundException{
      int a  =10;
      System.out.print(a);
      throw new ArrayIndexOutOfBoundsException();//无错
      //throw new FileNotFoundException;//有错
  }

错误和异常的不同

异常:可以捕获的.
错误:一般是不可处理的 例如 虚拟机挂了.

Java_异常_第1张图片
1.PNG

throws和throw的不同

  • throw是语句抛出一个异常
    • 语法 throw(异常对象); throw e;(自己不处理 抛给调用这调用)
  • throws是方法可能抛出异常的声明(用在声明方法时,表示该方法可能要抛出异常)
    • 语法:[(修饰符)(返回类型)(方法名)([参数列表])(throws(异常类型)){.......}

throws出现在方法函数头,而throw出现在函数体中.

你可能感兴趣的:(Java_异常)