

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Can the overriding method throw the super-type of the exception thrown by the overridden method in Java?
If the super-class method throws certain exception, the method in the sub-class should not throw its super type.
Example
In the following example the readFile() method of the super-class throws FileNotFoundException exception and, the readFile() method of the sub-class throws an IOException, which is the super type of the FileNotFoundException.
import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Scanner; abstract class Super { public String readFile(String path)throws FileNotFoundException { throw new FileNotFoundException(); } } public class ExceptionsExample extends Super { @Override public String readFile(String path)throws IOException { //method body ...... } }
Compile time error
On compiling, the above program gives you the following output −
ExceptionsExample.java:13: error: readFile(String) in ExceptionsExample cannot override readFile(String) in Sup public String readFile(String path)throws IOException { ^ overridden method does not throw IOException 1 error
- Related Questions & Answers
- While overriding can the subclass choose not to throw an exception in java?
- Exception handling with method overriding in Java.
- What are the rules of exception handling with respect to method overriding in java?
- Can the abstract methods of an interface throw an exception in java?
- Why is method overloading not possible by changing the return type of the method only in java?
- What are the rules on method overriding in Java?
- What is the difference between method hiding and method overriding in Java?
- What is the difference between method overloading and method overriding in Java?
- What is the purpose of overriding a finalize() method in Java?
- If a method in parent class “throws Exception”, can we remove it in overridden method in java?
- Method overriding in Java
- How to catch an exception thrown by an async void method in C#?
- How can an exception be thrown manually by a programmer in java?
- Get the declared method by name and parameter type in Java
- What are the rules need to follow when overriding a method that throws an exception in Java?
Advertisements