Sunday, 17 April 2011

What happens if a method does not throw an checked Exception directly but calls a method that does? What does 'Ducking' the exception mean?


If a method does not throw an checked Exception directly but calls a method that throws an exception then the calling method must handle the throw exception or declare the exception in its throws clause. If the calling method does not handle and declares the exception, the exceptions is passed to the next method in the method stack. This is called as ducking the exception down the method stack.
e.g. The code below will not compile as the getCar() method has not declared the CarNotFoundException which is thrown by the getColor () method.
void getCar() {
getColor();
}
void getColor () {
throw new CarNotFoundException();
}
Fix for the above code is
void getCar() throws CarNotFoundException {
getColor();
}
void getColor () {
throw new CarNotFoundException();
}

No comments:

Post a Comment