Is it possible to resume Java after an exception?

I have a ParentClass in a JAR, but not source code. I implement 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 after handling the exception in the override method? I do not want to duplicate the code and cannot change the ParentClass.

PS: The problem with NullPointerException was missing in the ParentClass. But due to another instance in SubClass this problem may occur.

+5
source share
2 answers

No.

You cannot just go back to the middle of the method.

If you do not want to copy-paste the code there (a good call!), You should put the general code in a separate method that your subclass can call.

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

But due to another instance in SubClass this problem may occur.

Perhaps you can get around the exception altogether by changing the way you create this instance? Maybe this is a "dummy object" for a thing that is currently null ? Something that does nothing harmful but prevents an exception?

+3
source

As others have pointed out, you cannot return there. However, you can refactor Parent.foo() something like this:

 class ParentClass { protected void foo() { // made it protected so it overridable stuffBeforeNPE(); // Extract Method Refactoring codeWithPossiblyNPE(); // Extract Method Refactoring stuffAfterNPE(); // Extract Method Refactoring } protected void stuffBeforeNPE() { ... } // you might want to add params and return values protected void codeWithPossiblyNPE() { ... } stuffAfterNPE() { ... } } 

Your child class might now look like this:

 class SubClass extends ParentClass { @Override protected void foo() { stuffBeforeNPE(); try { codeWithPossiblyNPE(); } catch(NullPointerException npe) { … /*handle exception*/ } stuffAfterNPE(); } } 
+2
source

Source: https://habr.com/ru/post/1271595/


All Articles