R2D2 R2D2 - 3 months ago 16
Java Question

Exception handling without try block

I think this is correct... When an exception occurs an object of the exception class is thrown and if we dont use a try or catch block, then the object goes to the JVM.
My question is why is the try block necessary, why wouldn't a catch block be good enough since the exception object is not created in the try block? I know that java requires you to use a try block to test the code in which the exception might occur, but was wondering if the exception object is created either way, then why couldn't a catch block been sufficient enough. This question is different from other exception handling questions in that it doesn't appear anyone has asked about needing to have the try block specifically.

Answer

The try { } portion indicates the section of code the catch { } block is protecting.

void test() {
    do_something();          // Not covered
    try {
       something_fixable();  // Covered
    } catch (InvalidStateException ex) {
       do_recovery_for_fixable_thing();
    }
}

Without the try { } block, the catch { } block might try to catch an exception other than the one it can handle.

Even if the exception thrown by do_something() is the same kind of exception, an InvalidStateException, the recovery code won't handle it; it isn't supposed to.

Comments