Using Exception Handling to Eliminate Irrelevant Exceptions in the Subclass Designer

I am writing a class in Java, which is a subclass of another class that I wrote, and its constructor explicitly calls the constructor of the superclass. A superclass constructor can throw several types of exceptions during initialization directly, however, when initializing an instance of my subclass, there are several exceptions that will never be thrown (by design).

I tried to catch these exceptions in the constructor of the subclass, but I got an error stating that "calling the constructor should be the first statement in the constructor." Why can't I take advantage of these exceptions?

For example, the code below:

public class Persian_Cat extends Cat { public Persian_Cat(File file) { try{ super(file); } catch(InvalidArgumentException e) { } catch(FileNotFoundException e) { } } } 

notes super(file); error super(file); like a mistake.

How can I implement a subclass constructor so that it knows that these exceptions do not matter? I need this because I do not want to wrap this constructor in try {} ... catch {} for each exception in my code later.

+6
source share
2 answers

Unfortunately, if you use super(...); , this should be the first line of code in the constructor. There is no way to avoid this.

One solution would be to create another constructor that does not throw these exceptions. It might be prudent to embrace this as protected rather than public. You would like to document the API to make it clear which input check (or something else) is failing due to what assumptions.

+6
source

If your first line is not an explicit call to the super constructor, the JVM will insert empty. Therefore, if you need to call a non-empty superconstructor, this should be the first line.

 public Persian_Cat(File file) throws InvalidArgumentException, FileNotFoundException { super(file); } 

JLS-8.8.7 reads (partially)

If the constructor body does not start with an explicit constructor call and the declared constructor is not part of the original Object class, then the constructor body implicitly starts with the constructor of the superclass "super ();", calling the constructor of its direct superclass that takes no arguments.

So when you ask why I cannot catch these exceptions? The answer is that Java does not provide a mechanism for this. You can mark the Persian_Cat constructor as throwing them. Or you can create another constructor that does not throw an exception or does not add the file installer to the supertype. Or maybe you need a Builder or Factory.

+1
source

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


All Articles