0

Why the following code is not getting compiled. Generally super is not allowed to be wrapped in try-catch, because if exception thrown in super shows that super didn't complete, so it shouldn't be wrapped. But what if I throw exception in the try catch block. This still indicates that the class is not constructed completely right. So java developers could have allowed this case when they throw exception in the try catch block around super right. Is there any reason for why this is not allowed. The other question which made this as duplicate asks about why the super has to be first statement in the constructor. But this one is regarding throwing different exception instead superclass's thrown exception.

class AA
{
    AA() throws FileNotFoundException
    {
        throw new FileNotFoundException();
    }
}
class BB extends AA
{
    BB() throws Exception
    {
        try
        {
            super();
        }
        catch(Exception e)
        {
            throws new Exception();
        }
    }
}


R Nanthak
  • 344
  • 3
  • 17
  • It is not just the fact `super()` or `this()` must be first (the JVM itself is OK with putting it later), and there are plans to relax this requirement for Java in [JEP draft: Statements before super()](https://openjdk.org/jeps/8300786). The problem of allowing a `super()` or `this()` to occur in a try-catch would allow you to ignore problems in initializing the object, and thus allow the construction of a partially initialized object, which is not a good thing. Even the proposed relaxation of the rules will not allow you to use try-catch. – Mark Rotteveel Mar 27 '23 at 09:27

1 Answers1

2

The JLD does not allow it. There could be multiple reasons why they do not allow it but i guess it is because a constructor is not a method it does not return any value. So it means there went something wrong with creating the class. In this case the initialization of the class went wrong and it is not guaranteed that it will work properly and it should be checked that all parameters given to the constructor should be correct before it is getting called.

samann
  • 73
  • 5
  • but, throwing exception in catch, still shows that class is not constructed well, so they could have allowed it right?. – R Nanthak Mar 15 '23 at 07:15
  • By “JLD” did you mean *The Java Language Specification* found [here](https://docs.oracle.com/javase/specs/)? – Basil Bourque Mar 15 '23 at 07:42