找到你要的答案

Q:Java Assertion in Try with multiple catchs

Q:java的断言在尝试多抓

Scenario:

class Assert {
    public static void main(String []args) {
        try {
            assert false;
        }
        catch (RuntimeException re) {
            System.out.println("In the handler of RuntimeException");
        }
        catch (Exception e) {
            System.out.println("In the handler of Exception");
        }
        catch (Error ae) {
            System.out.println("In the handler of Error");
        }
        catch (Throwable t) {
            System.out.println("In the handler of Throwable");
        }
    }
}

I am expecting 'In the handler of Error' because AssertionError is subclass of Error but it doesn't show anything and terminate normal. after then to check the out put I added this one catch handler before Error handler .

catch (AssertionError t) {
    System.out.println("In the handler of Throwable");
}

in know it's not a good practice to catch Error but if we does not need to catch why the program was not crashed it terminate normally?

脚本:

class Assert {
    public static void main(String []args) {
        try {
            assert false;
        }
        catch (RuntimeException re) {
            System.out.println("In the handler of RuntimeException");
        }
        catch (Exception e) {
            System.out.println("In the handler of Exception");
        }
        catch (Error ae) {
            System.out.println("In the handler of Error");
        }
        catch (Throwable t) {
            System.out.println("In the handler of Throwable");
        }
    }
}

我期待在错误处理程序的断言错误是因为错误的子类,但它不显示任何终止正常。然后检查外放我在错误处理之前添加了一个catch处理程序。

catch (AssertionError t) {
    System.out.println("In the handler of Throwable");
}

在知道这不是一个很好的做法,以赶上错误,但如果我们不需要赶上为什么程序没有崩溃,它通常终止?

answer1: 回答1:

By default assertions are disabled, add -ea in the command line when you execute your code with java:

java -ea Assert

默认情况下禁用添加断言,EA在命令行中执行你的代码,当你用java:

java -ea Assert
java  exception-handling  assert  assertions