Tuesday 24 June 2014

Method Overriding And Exception Handling

1. If a method declares to throw a given exception, then the overriding method in a subclass can only declare to throw that exception or its subclass.

Example 1
import java.io.*;
class SuperClass{
 public void print() throws IOException{
 
 }
}

import java.io.*;

class SubClass extends SuperClass{
 public void print() throws Exception{
 
 }
}

When tries to compile the SubClass.java, then compiler throws below error. Since print method in SubClass throws Exception which is super class of IOException. So Compiler thrown the error.

SubClass.java:4: error: print() in SubClass cannot override print() in SuperClass
        public void print() throws Exception{
                    ^
  overridden method does not throw Exception
1 error

Example 2
import java.io.*;

class SubClass extends SuperClass{
 public void print() throws IOException{
 
 }
}

Program compiles fine.

Example 3
import java.io.*;

class SubClass extends SuperClass{
 public void print() throws FileNotFoundException{
 
 }
}

Program compiles fine, since FileNotFoundException is sub class of IOException

2. The overriding method can throw any unchecked (runtime) exception, regardless of whether the overridden method declares the exception or not.

Example 1
import java.io.*;
class SuperClass{
 public void print() throws IOException{
 
 }
}

class SubClass extends SuperClass{
 public void print() throws NullPointerException{
 
 }
}
Program compiles fine, since NullPoinerException is unchecked exception.

Example 2
class SuperClass{
 public void print(){
 
 }
}

class SubClass extends SuperClass{
 public void print() throws NullPointerException{
 
 }
}

Program compiles fine. since NullPoinerException is unchecked exception.

Example 3
class SuperClass{
 public void print(){
 
 }
}

import java.io.*;

class SubClass extends SuperClass{
 public void print() throws IOException{
 
 }
}

Compiler throws below error, since IOException is checked Exception where print method in super class is not throwing any exception.

SubClass.java:4: error: print() in SubClass cannot override print() in SuperClass
        public void print() throws IOException{
                    ^
  overridden method does not throw IOException
1 error


You may like


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment