异常的分类

可查异常

可查异常:checkedException

可查异常,要么try catch 要么抛出,谁调用,谁处理,不然编译器不会编译通过

 1 import java.io.File;
 2 import java.io.FileInputStream;
 3 import java.io.FileNotFoundException;
 4   
 5 public class TestException {
 6   
 7     public static void main(String[] args) {
 8           
 9         File f= new File("d:/LOL.exe");
10           
11         try{
12             System.out.println("试图打开 d:/LOL.exe");
13             new FileInputStream(f);
14             System.out.println("成功打开");
15         }
16         catch(FileNotFoundException e){
17             System.out.println("d:/LOL.exe不存在");
18             e.printStackTrace();
19         }
20           
21     }
22 }

运行时异常

运行时异常RuntimeException:不是必须进行try catch异常

常见运行时异常:
  除数不能为0异常:ArithmeticException
  下标越界异常:ArrayIndexOutOfBoundsException
  空指针异常:NullPointerException

在编写代码的时候仍然进行try catch throws进行处理,与可查异常不同之处在于,即使不进行try catch编译仍然可以通过

Java设置运行时异常主要是因为,除数为0,下标越界经常出现,如果都进行捕捉,代码的可读性就会很糟糕

 1 public class TestException {
 2   
 3     public static void main(String[] args) {
 4          
 5         //任何除数不能为0:ArithmeticException
 6         int k = 5/0;
 7          
 8         //下标越界异常:ArrayIndexOutOfBoundsException
 9         int j[] = new int[5];
10         j[10] = 10;
11          
12         //空指针异常:NullPointerException
13         String str = null;
14         str.length();
15    }
16 }

错误

错误Error,指的是系统级别的异常,通常是内存用光了

 

posted @ 2020-02-02 16:10  东功  阅读(289)  评论(0编辑  收藏  举报