Java - find the first cause of an exception

后端 未结 10 989
渐次进展
渐次进展 2020-12-09 01:50

I need to check if an exception is caused by some database problem. I receive an Exception and check if its cause contains the \"ORA\" string and return that (something like

10条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-09 02:11

    One line solution using core Java API:

        try {
            i = 1 / 0; 
        } catch (ArithmeticException e) {
            System.out.println(new ArithmeticException().initCause(e).getCause());
        }
    

    One more solution below works as well:

        try {
            i = 1 / 0; 
        } catch (ArithmeticException e) {
            System.out.println(new Exception().initCause(e).getCause());
        }
    

    Both of them will print

    java.lang.ArithmeticException: / by zero

提交回复
热议问题