Java 异常与IO流

一、异常

  想想一下代码会发生什么?

public static void main(String[] args) {
        
        int a = 10;
        int b = 0;
        System.out.println(a/b);
        System.out.println("程序结束");
    }

我们都知道,当分母不能为0,所以程序会报错,这是非编译错误。

1、异常的概念:

  程序运行时,发生的不被期望的事件,它阻止了程序按照程序员的预期正常执行,这就是异常。

  异常是程序中的一些错误,比如说,你的代码少了一个分号,那么运行出来的结果是提示是错误:Java lang Error ;如果你用System.out.println(11/0),那么你是因为你用了0做了除数,会抛出java.lang.Arithmetic Exception 的异常。

  异常发生时,是任程序自生自灭,立刻退出终止,还是输入错误给用户?

  Java提供了优秀的解决办法:异常处理机制。

2、异常体系结构

  异常处理机制能让程序在异常发生时,按照代码的预先设定的异常处理逻辑,针对性的处理异常,让程序最大可能恢复正常并继续执行,且保持代码的清晰。

3、异常的分类

  throwable类

    Error 表示JVM异常,通常很少出现,也不需要程序员去处理

    Exception

      RuntimeException 运行时异常,(非检查异常)

      IOException (检查异常,除了Error和RuntimeException之外的都是检查异常)

 

 4、异常的使用

  对于异常,我们有三种处理方法

    1、捕获异常

      try{

        //可能出现异常的代码段

      }catch(ExceptionName e){

        //对异常进行处理的代码段

      }finally{

        //不管发不发生异常,都执行该模块下的内容

      }

示例:

    public static void main(String[] args) {
        
        int i = 10;
        int j = 0;
        
        try{        //首先程序进入try中,如果try中的代码没有出现异常,就执行try中的代码,然后打印程序结束
            System.out.println(i/j);
        }catch(ArithmeticException e){        //当try中带代码出现异常,就会执行catch中的代码,然后打印程序结束
            System.out.println("分母不能为0");
        }
        System.out.println("程序结束");
    
    }

 

控制台打印结果:分母不能为0

        程序结束

 

    2、声明异常

      在方法中使用throws关键字声明异常

示例:

    /**
     * 在方法上声声明一个异常
     * @param args
     * @throws ArithmeticException
     */
    public static void main(String[] args) throws ArithmeticException {
        
        System.out.println(11/0);
    }

    3、抛出异常

      try{

        //可能出现异常的代码段

      }catch(ExceptionName e){

        throw new Exception();

      }

示例:

    /**
     * fun方法在main方法中调用,可以选择捕获异常,也可以选择继续往外抛异常
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {    //在这里继续把异常往外抛
        fun(11,0);
    }
    
    /**
     * 在方法中声明创建一个异常,并往外抛异常
     * @param i
     * @param j
     * @throws Exception
     */
    public static void fun(int i ,int j) throws Exception{
        try{
            System.out.println(i/j);
        }catch(ArithmeticException e){
            throw new Exception("分母不能为0");
        }
        
    }

5、多重catch块

示例:

    public static void main(String[] args) {
        
        try {
            String[] arr = null; 
            System.out.println(arr[0]);
            FileInputStream io = new FileInputStream("");
        }catch (FileNotFoundException e){ 
            System.out.println(" 文件没找到 "); 
        }catch(NullPointerException e){
            System.out.println(" 对象为空 ");
            System. out.println(" 对象为空 "); 
        }
    }

  在安排catch语句的顺序时,首先应该捕获最特殊的异常,然后再逐渐一般化,即先子类后父类。

6、常见的异常类型

猜你喜欢

转载自www.cnblogs.com/sloth-007/p/10658949.html