Passing an exception up the calling chain

后端 未结 3 1491
迷失自我
迷失自我 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:52

    First, you'll have to add throws ABException to the main method and then either delete the block that catches the exception or rethrow it after logging

    throw ab;
    
    0 讨论(0)
  • 2021-02-06 15:54

    The "calling chain", also commonly known as "stack trace", is the list of all nested method calls leading to a single line of execution. In your case, its depth is 2 : main calls checkArray, but there can be dozens of methods.

    When an exception occurs in the code, it interrupts the current method and gives the control back to the previous method on the stack trace. If this method can handle the exception (with a catch), the catch will be executed, the exception will stop bubbling up. If not, the exception will bubble up the stack trace. Ultimately, if it arrives in the main and the main cannot handle it, the program will stop with an error.

    In your specific case, the throw new ABException() creates and throws an ABException that interrupts the checkArray method. The exception is then caught in your main with catch(ABException ab). So according to your question, you can say that this code passes the exception 'up the calling chain'.

    There are many more things to say, notably related to checked/unchecked exceptions. If you have some more specific questions, feel free to ask.

    0 讨论(0)
  • 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"

    0 讨论(0)
提交回复
热议问题