Call to super need to try / catch

I am working on an assignment where they tell me that I need to create a class (Call it ClassB) that should extend this class (name it ClassA). The only problem is that the code inside the ClassA constructor can throw an exception, so when I create my constructor for ClassB, I try to wrap the try / catch block around the call to super (), but of course this does not work, since super should be first call.

How can I get around this?

+4
source share
3 answers
public ClassB extends ClassA { public ClassB() throws MyClassAException { super(); } } 
+6
source

You can add your exception to the throws clause of your constructor subclass: -

 class ClassA { ClassA() throws Exception { } } public class Demo extends ClassA { Demo() throws Exception { super(); } public static void main(String[] args) { try { Demo d = new Demo(); // Handle exception here. } catch (Exception e) { e.printStackTrace(); } } } 
+1
source

ClassB must have a static method

 public static ClassB makeClassB() { try { return new ClassB(); } catch(Exception exc) { // whatever logic you are currently performing to swallow // presumably you have some default ClassB to return as part of this logic? } 

which completes the construction of ClassB with try / catch. The client code will call makeClassB() , and the constructor - ClassB will be private and throwing.

0
source

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


All Articles