Override method throws exception in java

What are the rules of exception handling with respect to method overriding in java?

While a superclass method throws an exception while overriding it you need to follow the certain rules.

Should throw Same exception or, sub type

If the super-class method throws certain exception, the method in the sub-class should throw the same exception or its sub type.

Example

In the following example, the readFile() method of the super-class throws an IOEXception and, the readFile() method of the sub-class throws FileNotFoundException exception.

Since the FileNotFoundException exception is the sub type of the IOException 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 String readFile(String path) throws IOException < throw new IOException(); >> public class ExceptionsExample extends Super < @Override public String readFile(String path) throws FileNotFoundException < Scanner sc = new Scanner(new File("E://test//sample.txt")); String input; StringBuffer sb = new StringBuffer(); while (sc.hasNextLine()) < input = sc.nextLine(); sb.append(" "+input); >return sb.toString(); > public static void main(String args[]) < String path = "E://test//sample.txt"; ExceptionsExample obj = new ExceptionsExample(); try < System.out.println(obj.readFile(path)); >catch(FileNotFoundException e) < System.out.println("Make sure the specified file exists"); >> >

Output

Tutorials Point is an E-learning company that set out on its journey to provide knowledge to that class of readers that responds better to online content. With Tutorials Point, you can learn at your own pace, in your own space. After a successful journey of providing the best learning content at tutorialspoint.com, we created our subscription based premium product called Tutorix to provide Simply Easy Learning in the best personalized way for K-12 students, and aspirants of competitive exams like IIT/JEE and NEET.

Example

In the same way if the sub-class throws the same exception as the super-class the program gets compiled and executed successfully.

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()throws FileNotFoundException < System.out.println("Method of Subclass"); >public static void main(String args[]) < ExceptionsExample obj = new ExceptionsExample(); obj.sampleMethod(); >>

Output

Should not throw an exception of super type

If the super-class method throws certain exception, the method in the sub-class should not throw its super type.

Читайте также:  Xml escape java string

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

Without throwing any exception

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(); >>

Источник

Override method throws exception in java

  • Introduction to Java
  • The complete History of Java Programming Language
  • C++ vs Java vs Python
  • How to Download and Install Java for 64 bit machine?
  • Setting up the environment in Java
  • How to Download and Install Eclipse on Windows?
  • JDK in Java
  • How JVM Works – JVM Architecture?
  • Differences between JDK, JRE and JVM
  • Just In Time Compiler
  • Difference between JIT and JVM in Java
  • Difference between Byte Code and Machine Code
  • How is Java platform independent?
  • Decision Making in Java (if, if-else, switch, break, continue, jump)
  • Java if statement with Examples
  • Java if-else
  • Java if-else-if ladder with Examples
  • Loops in Java
  • For Loop in Java
  • Java while loop with Examples
  • Java do-while loop with Examples
  • For-each loop in Java
  • Continue Statement in Java
  • Break statement in Java
  • Usage of Break keyword in Java
  • return keyword in Java
  • Object Oriented Programming (OOPs) Concept in Java
  • Why Java is not a purely Object-Oriented Language?
  • Classes and Objects in Java
  • Naming Conventions in Java
  • Java Methods
  • Access Modifiers in Java
  • Java Constructors
  • Four Main Object Oriented Programming Concepts of Java
  • Inheritance in Java
  • Abstraction in Java
  • Encapsulation in Java
  • Polymorphism in Java
  • Interfaces in Java
  • ‘this’ reference in Java

Источник

Override method throws exception in java

  • Introduction to Java
  • The complete History of Java Programming Language
  • C++ vs Java vs Python
  • How to Download and Install Java for 64 bit machine?
  • Setting up the environment in Java
  • How to Download and Install Eclipse on Windows?
  • JDK in Java
  • How JVM Works – JVM Architecture?
  • Differences between JDK, JRE and JVM
  • Just In Time Compiler
  • Difference between JIT and JVM in Java
  • Difference between Byte Code and Machine Code
  • How is Java platform independent?
  • Decision Making in Java (if, if-else, switch, break, continue, jump)
  • Java if statement with Examples
  • Java if-else
  • Java if-else-if ladder with Examples
  • Loops in Java
  • For Loop in Java
  • Java while loop with Examples
  • Java do-while loop with Examples
  • For-each loop in Java
  • Continue Statement in Java
  • Break statement in Java
  • Usage of Break keyword in Java
  • return keyword in Java
  • Object Oriented Programming (OOPs) Concept in Java
  • Why Java is not a purely Object-Oriented Language?
  • Classes and Objects in Java
  • Naming Conventions in Java
  • Java Methods
  • Access Modifiers in Java
  • Java Constructors
  • Four Main Object Oriented Programming Concepts of Java
  • Inheritance in Java
  • Abstraction in Java
  • Encapsulation in Java
  • Polymorphism in Java
  • Interfaces in Java
  • ‘this’ reference in Java

Источник

Exception Handling with Method Overriding in Java

Scientech Easy

Exception Handling with Method Overriding in Java | When a superclass method (overridden method) declares that it can throw an exception then subclass method (overriding method) must also declare that it can throw the same kind of exception or a sub type of that exception.

To handle the exception while you overriding a method in Java, you will have to follow three important rules. They are as follows:

1. If an overridden method does not throw an exception using throws clause then

  • The overriding method can not throw any checked or compile-time exception.
  • The overriding method can throw any unchecked or runtime exception.

2. If an overridden method throws an unchecked or runtime exception then

    • The overriding method can throw any unchecked or runtime exception.
    • The overriding method can throw the same exception which is thrown by the overridden method.
    • The overriding method can ignore the method level exception.

    3. If the superclass method throws checked or compile-time exception then

    • Subclass method can throw an exception which is a subclass of the superclass method’s exception.
    • Subclass method cannot throw the exception which is a superclass of the superclass method’s exception.
    • Subclass method can throw any unchecked or runtime exception.

    Rules of Exception Handling with Method Overriding in Java

    Look at the below figure to understand better.

    Let’s take different types of example programs based on these rules.

    Program source code 1:

    package overriding; public class Parent < // Overridden method is not throwing an exception. void msg() < System.out.println("msg-Parent"); >> import java.io.IOException; public class Child extends Parent < void msg() throws IOException // Compile-time error because the overriding method is throwing a checked exception. < System.out.println("msg-Child"); >public static void main(String[] args) throws IOException < Parent p = new Child(); p.msg(); Child c = new Child(); c.msg(); >>
    Output: Unresolved compilation problem: Exception IOException is not compatible with throws clause in Parent.msg()

    In the above example program, if overriding method throws an unchecked exception, there will be no compile-time error. Look at the program source code.

    package overriding; public class Parent < // Overridden method is not throwing an exception. void msg() < System.out.println(“msg-Parent”); >> import java.io.IOException; public class Child extends Parent < void msg() throws ArithmeticException // No compile-time error because the overriding method is throwing an unchecked exception. < System.out.println(“msg-Child”); >public static void main(String[] args) throws IOException < Parent p = new Child(); p.msg(); Child c = new Child(); c.msg(); >>

    Program source code 3:

    package overriding; public class Parent < // Overridden method is throwing an unchecked exception. void msg() throws ArithmeticException < System.out.println("msg-Parent"); >> public class Child extends Parent < void msg() throws ClassCastException // No Compile-time error because the overriding method is throwing an unchecked exception. < System.out.println("msg-Child"); >public static void main(String[] args) < Parent p = new Child(); p.msg(); Child c = new Child(); c.msg(); >>

    Q. What will be the error in the following program?
    Assumption X is superclass and Y is subclass.

    1. In superclass public void m1() throws IOException < System.out.println("Hello"); >In subclass public void m1() throws Exception

    A. Compile-time error because the overriding method is throwing an exception which is the superclass of the superclass method’ exception. i.e, Exception is the superclass of IOExecption.

    2. In superclass public void m1() throws Throwable < System.out.println("Parent"); >In subclass public void m1() throws Exception

    A. No compile-time error because Throwable is the superclass of all exceptions.

    3. In base class public void m1() throws Exception < System.out.println("Base"); >In derived class void m1() throws InterrurptedException

    A. Compile-time error because you cannot reduce the visibility of inherited method from Parent. Access modifiers must be bigger or same.

    4. In base class protected void m1() throws Exception < System.out.println("Base"); >In derived class public void m1() throws Exception

    A. No error.

    5. In superclass protected void m1(char c) throws Throwable < System.out.println("Parent"); >In subclass void m1(char c)

    A. Error because we cannot reduce the visibility while overriding method.

    Hope that this tutorial has covered almost all important rules of exception handling with method overriding in Java with example programs. I hope that you will have understood nicely this topic and enjoyed it.
    Thanks for reading.
    Next ⇒ Difference between overloading and overriding in Java

    Источник

Оцените статью