I do know that, constructor of a sub class can throw any exception but it must also throw exception from super class or its superclass exception.
My question is, in class Child when it says Exception will be thrown from Child() constructor, why not compiler complains something like,
already declared exception or unreachable or redundant throws for FileNotFoundException and IOException?
as both of these are subclasses of Exception.
Constructors don't override each other, like with methods! So the rule about which exceptions are allowed for overriding a method does not apply to constructors.
The Parent constructor can throw an IOException. So Child (a subclass of Parent) constructor must declare at least IOException, because super() will be invoked (which possible throws IOException). That's the only requirement for the Child constructor. But Child constructor itself can throw any other exception as well.
You can declare this method without any compiler errors, so why would it be different with constructors?
"someOtherMethodThatMightThrowOtherTypesOfException" should be either Checked or Unchecked, If unchecked, then no problem as it is not checked by the compiler, if checked then it will be taken care by Exception which is already thrown, is it not right?
Prathima gaitonde wrote: "someOtherMethodThatMightThrowOtherTypesOfException" should be either Checked or Unchecked, If unchecked, then no problem as it is not checked by the compiler, if checked then it will be taken care by Exception which is already thrown, is it not right?
Not completely correct!
Assume the someOtherMethodThatMightThrowOtherTypesOfException method throws a checked exception. You know you have to handle or declare this exception, otherwise you'll get a compiler error. So you could either add the appropriate checked exception (or the Exception class) to the throws clause of the constructor (as shown in the code snippet). Or you could put the method call in a catch block, as shown in this code snippet:
As always unchecked exceptions are not checked by the compiler, so you can handle and/or declare these exceptions, but it's not required.
Note: when you declare an exception in the throws clause of a method/constructor, it just indicates that this method/constructor could (sometimes) throw this exception. That statement is not throwing the exception, to actually throw an exception, you need a throw statement. An example:
And you know the drill by know, it's time for a pop quiz What about this code snippet, will it compile or not? And if not, what's the reason why it doesn't compile?