Fork me on GitHub

java_异常处理

cmd命令行下编译并执行,不过要将package javase8注释掉,否则会报错

D:\code\workspace\myjava\src\javase8>java Exception20171231
错误: 找不到或无法加载主类 Exception20171231

在命令行下传递参数,divide,null,test,hh

//package javase8;

class TestException extends Exception {
    TestException(){super();}
    TestException(String s){super(s);}
}

class Exception20171231 {

    public static void main(String[] args) {
        for (String arg : args) {
            try {
                thrower(arg);
                System.out.println("Test \"" + arg +"\" did't throw an exception");
            } catch (Exception e) {
                System.out.println("Test \"" + arg +"\" threw a " + e.getClass() + "\n    with message: " + e.getMessage());
            }
        }
    }

    static int thrower(String s) throws TestException{
        try {
            if (s.equals("divide")) {
                int i=0;
                return i/i;
            }
            if (s.equals("null")) {
                s=null;
                return s.length();
            }
            if (s.equals("test")) {
                throw new TestException("Test Message");
            }
            return 0;
        } finally {
            System.out.println("[thrower(\"" + s +"\") done]");
        }
    }
}

 

 

D:\code\workspace\myjava\src\javase8>javac Exception20171231.java

D:\code\workspace\myjava\src\javase8>java Exception20171231

D:\code\workspace\myjava\src\javase8>java Exception20171231 divide
[thrower("divide") done]
Test "divide" threw a class java.lang.ArithmeticException
        with message: / by zero

D:\code\workspace\myjava\src\javase8>java Exception20171231 null
[thrower("null") done]
Test "null" threw a class java.lang.NullPointerException
        with message: null

D:\code\workspace\myjava\src\javase8>java Exception20171231 test
[thrower("test") done]
Test "test" threw a class TestException
        with message: Test Message

D:\code\workspace\myjava\src\javase8>java Exception20171231 hh
[thrower("hh") done]
Test "hh" did't throw an exception

D:\code\workspace\myjava\src\javase8>

posted on 2017-12-31 14:33  阳光-源泉  阅读(192)  评论(0编辑  收藏  举报

导航