17

This is my code block.

class Alpha{
    public void Gamma() {
        System.out.println("Alphas");
    }
}

class Beta extends Alpha{
    public void Gamma() throws Exception //Line 1
    {
        try {
            System.out.println("Betas");
        } catch(Exception e) {
            System.out.println("Exception caught");
        } finally {
            System.out.println("xfg");
        }
    }
    public static void main(String[] args) throws Exception {
        Alpha g = new Beta();
        g.Gamma();
    }
}

This code fails to compile because I have added "throws" in Line1.

The compiler complains that overridden methods cannot throw exceptions.

Why so ?.

Why cant an overridden method throw an exception ?.

Because I can override a method from a base class by adding n lines of code in the child's class implementation.

And these added code can throw an exception so why I cant use "throws" in the overridden method ?.

Cœur
  • 37,241
  • 25
  • 195
  • 267
UnderDog
  • 3,173
  • 10
  • 32
  • 49
  • 2
    I think you answered your own question in the title. Overridden methods are bound by the contract in the definition of the superclass method. According to class **Alpha**, **Gamma()** doesn't throw an exception. You can't change a method's arguments, return types, or apparently exceptions when you override a method. – Edward Falk Aug 25 '13 at 05:56
  • 1
    A lot of people think that checked exceptions in Java were a mistake. You could just throw a [RuntimeException](http://docs.oracle.com/javase/7/docs/api/java/lang/RuntimeException.html) (which is unchecked) instead and avoid this problem. – DaoWen Aug 25 '13 at 05:56
  • @EdwardFalk Not entirely true. You can override the method with a stricter contract. – Chris Bode Aug 25 '13 at 06:03
  • Which page do you think google finds asked for [overriden methods java exception][1]? And, please note, the page returned is not this one. So, why do you think there are not duplicates? [1] https://www.google.ee/search?q=overridden+methods+java+exception – Val Aug 25 '13 at 06:15
  • @ChrisBode ahh, didn't know that. Although now that I think of it, you can also expose a method was was private in the superclass IIRC – Edward Falk Aug 25 '13 at 17:04

6 Answers6

31

Overridden methods can throw Exceptions, so long as the method being overridden also throws the same Exceptions. You can't introduce new Exceptions.

So why can't you introduce a new Exception?

One of the central concepts of OOP is using abstract types, and that all subtypes may be treated as the abstract type. See Liskov Substitution Principle

The reason you can't introduce broader behaviour is that if the method from the abstract type (super class or interface) doesn't throw an Exception and you refer to your object as that type, you'd get unexpected behaviour:

Alpha alpha = new Beta();
// At this point, the compiler knows only that we have an Alpha
alpha.myMethod();

If Alpha's myMethod() doesn't throw an Exception, but Beta's does, we could get an unexpected Exception in the above code.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • 1
    This isn't quite correct answer. Overriding method can throw some exceptions (e.g. `ClassCastException`, `RuntimeException`) even when the overridden method doesn't throw anything. Point is, that overriding method cannot throw wider than the overridden method's `Checked Exception`. – Giorgi Tsiklauri Aug 07 '21 at 17:25
  • 1
    @GiorgiTsiklauri Actually, you are incorrect. This answer is completely correct: *All* methods may throw unchecked exceptions, whether declared or not. This means that the overridden method can throw as many unchecked exceptions as it likes. The overriding method may do likewise, but the rule holds true that the overriding method may not throw *more* exceptions than the method being overridden. The compiler only compares method signatures, not method implementations, when checking if the overriding method is legal (requiring that checked exceptions be declared as thrown notwithstanding). – Bohemian Aug 07 '21 at 22:27
  • Actually, I think, that you are incorrect in your answer. Look: 1) your comment contradicts whatever you wrote in the answer: "*Overridden methods can throw Exceptions, so long as the method being overridden also throws the same Exceptions. You can't introduce new Exceptions.*" - which is wrong even for checked exceptions, as (1) overriding method can throw **any** unchecked, and only **covariant checked** exceptions of the overridden method (either same, or wider/extender - not broader/more-super). That's why I claimed in my previous comment. :) – Giorgi Tsiklauri Aug 08 '21 at 19:36
8

Subclass overriden method/methods can throw (Declare) only unchecked exception like ArrayIndexOutOfBoundsException.

But you can't throws (declare) the checked exception. like IOException.

example to overridden methods throw exceptions Java

class A{
 public void show(){
   // some code here
  }
}

class B extends A{
public void show() throws ArrayIndexOutOfBoundsException{
   // some code here
  }
}

Hope these may help you.

Brooklyn99
  • 987
  • 13
  • 24
PVH
  • 788
  • 1
  • 7
  • 12
4

Your client side always think to deal with the base version. That's the whole benefit of polymorphism => client side ignores the overriden one.

Thus, nothing will force the client to deal with specific rules made by the overriden, here the case of a potential exception thrown by the overidden method.

That's why an overriden method can't throw broader exceptions. It would break the contract.

Thus, regarding this logic, rule is: Overriden method CAN (if it want) only throw a subpart of the exceptions declared in the base version BUT CANNOT throw broader ones.

Mik378
  • 21,881
  • 15
  • 82
  • 180
1

The rule says

"Subclass overridden method cannot throw more exceptions than that of super class method".

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
1

The compiler complains that overridden methods cannot throw exceptions

No it doesn't. Read the message again. It says you can't throw an exception that isn't declared to be thrown by the overridden method. Not the same thing at all.

user207421
  • 305,947
  • 44
  • 307
  • 483
0

your above code in main method

Alpha g = new Beta(); // now it's create a new actual object of Beta class with refrence of Alpha

g.Gamma(); // * now compiler look only Gamma() method presents in Alpha class off cource it present in Beta class also by default through inheritance.but compiler looked only at class Alpha and ask a question is contains a method Gamma() and found a answer yes it has.

suppose a condition when java compiler gives facility to throws more checked exceptions in gamma() method in Beta Class then what will happen

  • now at compile time compiler only depend on Gamma() method of class Alpha.it does not force to handle this exception or throws this exception which is wrong because it might throw(supposing to java compiler allow throwing more checked exception in overridden method). but in reality compiler not make restriction on throwing exceptions but also on accessibility modifier.

    because non static method invocation happen on actual object method not on type and we give to any super type and at compilation time compiler only check accessibility and presence in that type of assigned class.

so i think that's the reason behind this overridden contract

• The method definition cannot narrow the accessibility of the method, but it can widen it. • The method definition can only throw all or none, or a subset of the checked exceptions (including their subclasses) that are specified in the throws clause of the overridden method in the superclass.

vikas singh
  • 131
  • 1
  • 2
  • 10