Passing an exception up the calling chain

后端 未结 3 1492
迷失自我
迷失自我 2021-02-06 15:30

Was hoping for an explanation as to what it means to pass an exception up the calling chain by declaring the exception in my methods throws clause and why I would want to do tha

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-06 15:56

    You can do it for example by not catching it in main(), but passing it to the piece of logic that called main(). In this case, it's trivial, as main() is your program's entry point...

    You could also rewrite your method

    void checkArray() throws ABException {
        for (int i = 0; i < charArray.length; i++) {
            check(charArray[i]);
        }
    }
    
    void check(char c) throws ABException {
        switch (c) {
            case 'a':
                throw new ABException();
            case 'b':
                throw new ABException();// creating the instance of the
                                        // exception anticipated
            default:
                System.out.println(c + " is not A or a B");
        }
    }
    

    Now it becomes more clear how checkArray() "passes the exception from check() up the calling chain"

提交回复
热议问题