5.14异常

来源:互联网 发布:linux文件同步 编辑:程序博客网 时间:2024/04/29 16:42

(1)处理异常:

try{//一些会抛出异常的方法}catchException e){//处理该异常的代码块}

catch可以有多个,接收不同的异常,顺序为子到父,因为捕获异常时是就近匹配catch的

catch(InputMismatchException e){}catch(ArithmeticException e){}catchException e){    e.printStackTrace();//可打印异常具体信息}finally{//最终将执行的一些代码}

finally语句块是在try和catch块的return语句执行完之后返回到调用者之前执行的。
(2)java中的异常抛出:
throw–将产生的抛出异常(写在方法体中)
throws–声明将要抛出何种类型的异常(可抛出多种异常,用逗号分开)
throw的两种用法:
1.throw在try中用catch捕获异常
2.丢给上一层处理:

public void computer() throws Exception{    divide(5,0);//该函数中有throw}

(3)自定义异常:
class 自定义异常类 extends 异常类型(意思相近的异常或基类){
}

public class DrunkException extends Exception {    public DrunkException(){    }    public DrunkException(String message){        super(message);    }}

(4)异常链:

public class ChainTest {    /**     * test1():抛出“喝大了”异常     * test2():调用test1(),捕获“喝大了”异常,并且包装成运行时异常,继续抛出     * main方法中,调用test2(),尝试捕获test2()方法抛出的异常     */    public static void main(String[] args) {        ChainTest ct = new ChainTest();        try{            ct.test2();        }catch(Exception e){            e.printStackTrace();        }    }    public void test1() throws DrunkException{        throw new DrunkException("喝酒别开车!");    }    public void test2(){        try {            test1();        } catch (DrunkException e) {            // TODO Auto-generated catch block            RuntimeException newExc =                 new RuntimeException(e);//          newExc.initCause(e);            throw newExc;        }    }}

运行结果:

java.lang.RuntimeException: com.imooc.test.DrunkException: 喝车别开酒!    at com.imooc.test.ChainTest.test2(ChainTest.java:29)    at com.imooc.test.ChainTest.main(ChainTest.java:13)Caused by: com.imooc.test.DrunkException: 喝车别开酒!    at com.imooc.test.ChainTest.test1(ChainTest.java:20)    at com.imooc.test.ChainTest.test2(ChainTest.java:25)    ... 1 more

(5)e.getMessage():得到异常的String
Exception exc=new Exception(“该图书不存在”);//通过String初始化异常
exc.initCause(e);//设定该异常由另一个异常引发
(6)scan.next()可以得到字符串;

0 0
原创粉丝点击