Skip to content
Advertisement

Is it possible to resume Java execution after exception?

I have a ParentClass in a JAR, but not source code. I am implementing a SubClass, but i need to handle some corner cases.

class ParentClass {
    void foo() {
       … // lots of code 1
       ; // can possibly throw NullPointerException 
       … // lots of code 2
    }
}
class SubClass extends ParentClass {
    @Override
    void foo() {
       try {super.foo();}
       catch(NullPointerException npe) {… /*handle exception*/}
       finally {… /* resume lots of code 2 ? */}
    }
}

Is there a way to run the //lots of code 2 part after handling the exception in the overriding method? I don’t want to duplicate code, and cannot modify the ParentClass.

P.S: The NullPointerException problem wasn’t there in the ParentClass. But due to a different instantiation in SubClass, this problem may arise.

Advertisement

Answer

No.

You cannot just jump back into the middle of a method.

If you don’t want to copy-paste the code in there (good call!) you have to put the shared code into a separate method that your subclass can call.

Or you could put the part that might throw the NullPointerException into a separate method and override it in the subclass (so that it no longer throws).

But due to a different instantiation in SubClass, this problem may arise.

Maybe you can sidestep the exception altogether by changing the way you do this instantiation? Maybe provide a “dummy object” for the thing that is currently null? Something that doesn’t do anything harmful, but prevents the exception?

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement