`
jarod2008
  • 浏览: 80531 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

java异常处理机制

    博客分类:
  • java
阅读更多

看例子最好了了,先贴上来java language spec中的一个经典例子。

 

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

    TestException(String s) {
        super(s);
    }
}

public class Test {
    public static void main(String[] args) {
        for (String arg : args) {
            try {
                thrower(arg);
                System.out
                        .println("Test \""
                                + arg
                                + "EXCEPTIONS An Example of Exceptions 11.405\" didn'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]");
        }
    }
}

 

然后运行 java divide null not test

得到的结果如下:

[thrower("divide") done]
Test "divide" threw a class java.lang.ArithmeticException
 with message: / by zero
[thrower("null") done]
Test "null" threw a class java.lang.NullPointerException
 with message: null
[thrower("not") done]
Test "notEXCEPTIONS An Example of Exceptions 11.405" didn't throw an exception
[thrower("test") done]
Test "test" threw a class TestException
 with message: Test message

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics