-2

This is my code:

 import java.io.*;
 import java.sql.*;
 import java.io.*;
 import java.sql.*;
 class Vehicle{
    public void park()throws IOException {//compiletime checked     
    }
 }
 class Car extends Vehicle{
     public void park()throws RuntimeException{//compile time unchecked
         //
     }  
 }

Why compile time unchecked exceptions is legal here?

GhostCat
  • 137,827
  • 25
  • 176
  • 248
Malinda
  • 524
  • 2
  • 5
  • 11

2 Answers2

1

It is legal because:

  • restricting derived methods is OK (if you are prepared to catch an io exception you have no problem if no such exception is thrown).
  • putting up RuntimeException is always possible because it is not a checked exception - so the compiler does not care anyway.

So your subclass simply overrides a method dropping a checked exception from the signature.

This is all rooted in the Liskov substitution principle: the idea is that you must be able to perform any call that is possible on a super class method also on the derived class.

When you think about this requirement it becomes clear quickly that it is perfectly fine when a derived method returns or throws "less" than the super class method.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
1

If superclass method throws/declare checked/compileTime exception, then--

overridden method of subclass can declare/throw narrower (subclass of) checked exception

overridden method of subclass cannot declare/throw broader (superclass of) checked exception

overridden method of subclass can declare/throw any unchecked /RuntimeException

overridden method of subclass can declare/throw same exception

overridden method of subclass may not declare/throw any exception.

Sanjay Singh
  • 307
  • 1
  • 3
  • 13