Java简明教程 11.异常

异常的感性认识html

没有异常机制的语言中,常常经过返回值来表示调用该函数产生的各类问题(异常),好比c语言.java

divide.c程序员

#include <stdio.h>

int main() {
    if (-1 == divide(1, 1)) {
        printf("除数不能为0.\n");
    }   
}


int divide(int divident, int divisor) {
    //若是除数为0,则返回-1
    if (0 == divisor) {
        return -1; 
    }   


    //若是除法不为0,则返回0
    printf("%d\n", divident/divisor);
    return 0;
}

 

在java中,经过它的异常处理机制,能够对异常进行处理.ide

Divide.java函数

public class Divide {
    public static void main(String[] args) {
        //把有可能产生异常的句子放在try{}语句中
        try {
            divide(1, 0); 
        }
        //经过catch(){}语句对异常进行处理. 注意:能够有多个catch(){}语句,由于有多个异常嘛
        catch(Exception e) {
            e.printStackTrace();
        }
        //finally{}里面的程序块,不管有没有异常,都会执行,多用于关闭资源.(..粗俗的说,也能够说是插屁股的")
        //注: finally{}能够省略,但try{} catch(){}不行!
        finally {
            System.out.println("白白");
        }

        System.out.println("注意:对异常处理以后,后面的句子仍旧执行.");
    }


    public static int divide(int i, int j) {
        int result = i / j;
        return result;
    }   
}

 

异常的类型this

如上图:(来源http://www.cnblogs.com/vamei/archive/2013/04/09/3000894.html)spa

橙色的表示不能够处理的异常, 蓝色的表示能够处理的异常.code

其中,htm

Error(以及其衍生类)是系统错误(好比 内存不足, java内部错误等等), 这个咱们程序员是没法处理的.对象

Exception下的衍生类 "RuntimeException", 这个是java程序自己有问题,也就是"bug"形成的. 好比"NullPointerException", "IndexOutOfBoundsException",  "ClassCastException"等等. 若是出现这些异常, 首先不是"try   catch", 而是检查本身代码是否出问题了

继承了Exception又不是RuntimeException的子类,也就是上图蓝色部门的异常,咱们就须要处理了.这些异常每每是在与用户交互的时候产生的,好比用户想要读取一个不存在的文件, 这个时候,就会出现"FileNotFoundException"异常. 这个咱们就必须处理了

 

 

总结:抛出异常对象(throw), 不对异常进行处理,将异常交给上层处理(throws),本身处理异常(try catch)

Demo.java

/* Exception in thread "main" java.lang.Exception: w的值不能为负数!
 *  at Cup.test(Demo.java:32)
 *      at Cup.addWater(Demo.java:16)
 *          at Demo.main(Demo.java:4)
 */
public class Demo {
    public static void main(String[] args) throws Exception {
        Cup cup = new Cup();
        cup.addWater(-1.0);
    }   
}

class Cup {
    private double water = 0.0;
    private double maxWater = 100.0;        //杯子的最大容量为100.0ml

    public void addWater(double w) throws Exception {
        test(w);
        //若是要加的水+原本拥有的水的体积小雨水杯的最大容量,那么就 "this.water = w + this.water"
        //不然,水溢出,直接设置 water = 最大容量 100ml便可
        if (w + this.water < maxWater) {
            this.water = w + this.water;
        } else {
            this.water = 100.0;
        }   
    }   
        
    //检查w的值是否正确,也就是检查w是否是整数
    public void test(double w) throws Exception {
        if (w < 0) {
            Exception e = new Exception("w的值不能为负数!");
            throw e;
        }   总结:抛出异常对象(throw), 不对异常进行处理,将异常交给上层处理(throws),本身处理异常(try catch)
    }   
}

 

自定义异常

DIYException.java

public class DIYExcetpion extends Exception {
    public DIYException(){}

    //在自定义异常的时候,要选择更具体的类,这样会包含更多的异常信息
    public DIYException(String message) {
        super(message);
    }   
}
相关文章
相关标签/搜索