Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
If a method in parent class “throws Exception”, can we remove it in overridden method in java?
While a superclass method throws an exception while overriding it you need to follow the certain rules.
- The sub class method Should throw Same exception or, sub type −
- It should not throw an exception of super type −
- You may leave the method in sub class Without throwing any exception
According to the 3rd rule, if the super-class method throws certain exception, you can override it without throwing any exception.
Example
In the following example the sampleMethod() method of the super-class throws FileNotFoundException exception and, the sampleMethod() method does not throw any exception at all. Still this program gets compiled and executed without any errors.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
abstract class Super{
public void sampleMethod()throws FileNotFoundException{
System.out.println("Method of superclass");
}
}
public class ExceptionsExample extends Super{
public void sampleMethod() {
System.out.println("Method of Subclass");
}
public static void main(String args[]) {
ExceptionsExample obj = new ExceptionsExample();
obj.sampleMethod();
}
}
Output
Method of Subclass
Advertisements