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 that.
Here is an example of my understanding of throwing own exception.
public class ExceptionThrow {
char[] charArray = new char[] { 'c', 'e', 'a', 'd' };
void checkArray() throws ABException {
for (int i = 0; i < charArray.length; i++) {
switch (charArray[i]) {
case 'a':
throw new ABException();
case 'b':
throw new ABException();// creating the instance of the
// exception anticipated
default:
System.out.println(charArray[i] + " is not A or a B");
}
}
}
public static void main(String[] args) {
ExceptionThrow et = new ExceptionThrow();
try {
et.checkArray();
} catch (ABException ab) {
System.out.println(ab.getMessage() + " An exception did actually occur");
} finally {
System.out.println("This block will always execute");
}
}
}
class ABException extends Exception {
}
How would I pass the exception 'up the calling chain'?
regards Arian
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With