(Translated by https://www.hiragana.jp/)
Exception Handling with Method Overriding in Java - GeeksforGeeks
Open In App

Exception Handling with Method Overriding in Java

Last Updated : 09 Aug, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

An Exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run-time, that disrupts the normal flow of the program’s instructions. Exception handling is used to handle runtime errors. It helps to maintain the normal flow of the program. 
In any object-oriented programming language, Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. When a method in a subclass has the same name, same parameters or signature, and same return type(or sub-type) as a method in its super-class, then the method in the subclass is said to override the method in the super-class.

Exception Handling with Method Overriding
When Exception handling is involved with Method overriding, ambiguity occurs. The compiler gets confused as to which definition is to be followed. 

Types of problems:

There are two types of problems associated with it which are as follows:

  1. Problem 1 If The SuperClass doesn’t declare an exception
  2. Problem 2: If The SuperClass declares an exception

Let us discuss different cases under these problems and perceived their outputs.

Problem 1 If The SuperClass doesn’t declare an exception

In this problem, two cases that will arise are as follows:

  • Case 1: If SuperClass doesn’t declare any exception and subclass declare checked exception
  • Case 2: If SuperClass doesn’t declare any exception and SubClass declare Unchecked exception

Let us discuss the above two cases and interpret them with help of examples as follows:

Case 1: If SuperClass doesn’t declare any exception and subclass declare checked exception.

Example 

Java




// Java Program to Illustrate Exception Handling
// with Method Overriding
// Where SuperClass does not declare any exception and
// subclass declare checked exception
 
// Importing required classes
import java.io.*;
 
class SuperClass {
 
  // SuperClass doesn't declare any exception
  void method() {
    System.out.println("SuperClass");
  }
}
 
// SuperClass inherited by the SubClass
class SubClass extends SuperClass {
 
  // method() declaring Checked Exception IOException
  void method() throws IOException {
 
    // IOException is of type Checked Exception
    // so the compiler will give Error
 
    System.out.println("SubClass");
  }
 
  // Driver code
  public static void main(String args[]) {
    SuperClass s = new SubClass();
    s.method();
  }
}


Output:

Case 2: If SuperClass doesn’t declare any exception and SubClass declare Unchecked exception

Example 

Java




// Java Program to Illustrate Exception Handling
// with Method Overriding
// Where SuperClass doesn't declare any exception and
// SubClass declare Unchecked exception
 
// Importing required classes
import java.io.*;
 
class SuperClass {
 
    // SuperClass doesn't declare any exception
    void method()
    {
        System.out.println("SuperClass");
    }
}
 
// SuperClass inherited by the SubClass
class SubClass extends SuperClass {
 
    // method() declaring Unchecked Exception ArithmeticException
    void method() throws ArithmeticException
    {
 
        // ArithmeticException is of type Unchecked Exception
        // so the compiler won't give any error
 
        System.out.println("SubClass");
    }
 
    // Driver code
    public static void main(String args[])
    {
        SuperClass s = new SubClass();
        s.method();
    }
}


Output

SubClass

Now dwelling onto the next problem associated with that is if The SuperClass declares an exception. In this problem 3 cases will arise as follows:

  • Case 1: If SuperClass declares an exception and SubClass declares exceptions other than the child exception of the SuperClass declared Exception.
  • Case 2: If SuperClass declares an exception and SubClass declares a child exception of the SuperClass declared Exception.
  • Case 3: If SuperClass declares an exception and SubClass declares without exception.

Now let us interpret these cases by implementing and interpreting with example. 

Case 1: If SuperClass declares an exception and SubClass declares exceptions other than the child exception of the SuperClass declared Exception.

Example 

Java




// Java Program to Illustrate Exception Handling
// with Method Overriding
// Where SuperClass declares an exception and
// SubClass declares exceptions other than the child exception
// of the SuperClass declared Exception.
 
// Importing required classes
import java.io.*;
 
class SuperClass {
 
  // SuperClass declares an exception
  void method() throws RuntimeException {
    System.out.println("SuperClass");
  }
}
 
// SuperClass inherited by the SubClass
class SubClass extends SuperClass {
 
  // SubClass declaring an exception
  // which are not a child exception of RuntimeException
  void method() throws Exception {
 
    // Exception is not a child exception
    // of the RuntimeException
    // So the compiler will give an error
 
    System.out.println("SubClass");
  }
 
  // Driver code
  public static void main(String args[]) {
    SuperClass s = new SubClass();
    s.method();
  }
}


Output:

Case 2: If SuperClass declares an exception and SubClass declares a child exception of the SuperClass declared Exception.

Example

Java




// Java Program to Illustrate Exception Handling
// with Method Overriding
// Where SuperClass declares an exception and
// SubClass declares a child exception
// of the SuperClass declared Exception
 
// Importing required classes
import java.io.*;
 
class SuperClass {
 
    // SuperClass declares an exception
    void method() throws RuntimeException
    {
        System.out.println("SuperClass");
    }
}
 
// SuperClass inherited by the SubClass
class SubClass extends SuperClass {
 
    // SubClass declaring a child exception
    // of RuntimeException
    void method() throws ArithmeticException
    {
 
        // ArithmeticException is a child exception
        // of the RuntimeException
        // So the compiler won't give an error
        System.out.println("SubClass");
    }
 
    // Driver code
    public static void main(String args[])
    {
        SuperClass s = new SubClass();
        s.method();
    }
}


Output

SubClass

Case 3: If SuperClass declares an exception and SubClass declares without exception.

Example

Java




// Java Program to Illustrate Exception Handling
// with Method Overriding
// Where SuperClass declares an exception and
// SubClass declares without exception
 
// Importing required classes
import java.io.*;
 
class SuperClass {
 
    // SuperClass declares an exception
    void method() throws IOException
    {
        System.out.println("SuperClass");
    }
}
 
// SuperClass inherited by the SubClass
class SubClass extends SuperClass {
 
    // SubClass declaring without exception
    void method()
    {
        System.out.println("SubClass");
    }
 
    // Driver code
    public static void main(String args[])
    {
        SuperClass s = new SubClass();
    try {
        s.method();
    } catch (IOException e) {
        e.printStackTrace();
    }
    }
}


Output

SubClass

Conclusions:

As perceived from above 3 examples in order to handle such exceptions, the following conclusions derived are as follows: 

  • If SuperClass does not declare an exception, then the SubClass can only declare unchecked exceptions, but not the checked exceptions.
  • If SuperClass declares an exception, then the SubClass can only declare the same or child exceptions of the exception declared by the SuperClass and any new Runtime Exceptions, just not any new checked exceptions at the same level or higher.
  • If SuperClass declares an exception, then the SubClass can declare without exception.


Previous Article
Next Article

Similar Reads

Comparison of Exception Handling in C++ and Java
Both languages use to try, catch and throw keywords for exception handling, and their meaning is also the same in both languages. Following are the differences between Java and C++ exception handling: Java C++ Only throwable objects can be thrown as exceptions.All types can be thrown as exceptions.We can catch Exception objects to catch all kinds o
4 min read
Java | Exception Handling | Question 1
Predict the output of following Java program class Main { public static void main(String args[]) { try { throw 10; } catch(int e) { System.out.println("Got the Exception " + e); } } } (A) Got the Exception 10 (B) Got the Exception 0 (C) Compiler Error Answer: (C) Explanation: In Java only throwable objects (Throwable objects are instances
1 min read
Java | Exception Handling | Question 2
class Test extends Exception { } class Main { public static void main(String args[]) { try { throw new Test(); } catch(Test t) { System.out.println("Got the Test Exception"); } finally { System.out.println("Inside finally block "); } } } (A) Got the Test Exception Inside finally block (B) Got the Test Exception (C) Inside finall
1 min read
Java | Exception Handling | Question 3
Output of following Java program? class Main { public static void main(String args[]) { int x = 0; int y = 10; int z = y/x; } } (A) Compiler Error (B) Compiles and runs fine (C) Compiles fine but throws ArithmeticException exception Answer: (C) Explanation: ArithmeticException is an unchecked exception, i.e., not checked by the compiler. So the pro
1 min read
Java | Exception Handling | Question 4
class Base extends Exception {} class Derived extends Base {} public class Main { public static void main(String args[]) { // some other stuff try { // Some monitored code throw new Derived(); } catch(Base b) { System.out.println("Caught base class exception"); } catch(Derived d) { System.out.println("Caught derived class exception
1 min read
Java | Exception Handling | Question 8
class Test { public static void main (String[] args) { try { int a = 0; System.out.println ("a = " + a); int b = 20 / a; System.out.println ("b = " + b); } catch(ArithmeticException e) { System.out.println ("Divide by zero error"); } finally { System.out.println ("inside the finally block"); } } } (A) Compile
1 min read
Java | Exception Handling | Question 6
class Test { public static void main(String[] args) { try { int a[]= {1, 2, 3, 4}; for (int i = 1; i <= 4; i++) { System.out.println ("a[" + i + "]=" + a[i] + "\n"); } } catch (Exception e) { System.out.println ("error = " + e); } catch (ArrayIndexOutOfBoundsException e) { System.out.println ("ArrayIn
1 min read
Java | Exception Handling | Question 7
Predict the output of the following program. class Test { String str = "a"; void A() { try { str +="b"; B(); } catch (Exception e) { str += "c"; } } void B() throws Exception { try { str += "d"; C(); } catch(Exception e) { throw new Exception(); } finally { str += "e"; } str += "f"; } void
1 min read
Java | Exception Handling | Question 8
Predict the output of the following program. class Test { int count = 0; void A() throws Exception { try { count++; try { count++; try { count++; throw new Exception(); } catch(Exception ex) { count++; throw new Exception(); } } catch(Exception ex) { count++; } } catch(Exception ex) { count++; } } void display() { System.out.println(count); } publi
1 min read
Java - Exception Handling With Constructors in Inheritance
Java provides a mechanism to handle exceptions. To learn about exception handling, you can refer to exceptions in java. In this article, we discuss exception handling with constructors when inheritance is involved. In Java, if the constructor of the parent class throws any checked exception, then the child class constructor can throw the same excep
7 min read
Output of Java program | Set 12(Exception Handling)
Prerequisites : Exception handling , control flow in try-catch-finally 1) What is the output of the following program? public class Test { public static void main(String[] args) { try { System.out.printf("1"); int sum = 9 / 0; System.out.printf("2"); } catch(ArithmeticException e) { System.out.printf("3"); } catch(Exce
3 min read
Nested try blocks in Exception Handling in Java
In Java , we can use a try block within a try block. Each time a try statement is entered, the context of that exception is pushed onto a stack. Given below is an example of a nested try. In this example, the inner try block (or try-block2) is used to handle ArithmeticException, i.e., division by zero. After that, the outer try block (or try-block)
3 min read
Difference Between Method Overloading and Method Overriding in Java
The differences between Method Overloading and Method Overriding in Java are as follows: Method Overloading Method Overriding Method overloading is a compile-time polymorphism.Method overriding is a run-time polymorphism.Method overloading helps to increase the readability of the program.Method overriding is used to grant the specific implementatio
4 min read
Exception handling in JSP
Java Server Pages declares 9 implicit objects, the exception object being one of them. It is an object of java.lang.Throwable class, and is used to print exceptions. However, it can only be used in error pages. There are two ways of handling exceptions in JSP. They are: By errorPage and isErrorPage attributes of page directiveBy <error-page>
3 min read
Exception Handling in Apache Kafka
Exception handling is an important aspect of any software system, and Apache Kafka is no exception. In this article, we will discuss the various types of exceptions that can occur in a Kafka system and how to handle them. First, it is important to understand the basic architecture of Kafka. A Kafka system consists of a number of brokers, which are
6 min read
Servlet - Exception Handling
When a servlet throws an exception, the web container looks for a match with the thrown exception type in web.xml configurations that employ the exception-type element. To define the invocation of servlets in response to particular errors or HTTP status codes, you'd have to utilize the error-page element in web.xml. Exception Handling is the proces
4 min read
Spring MVC - Exception Handling
Prerequisites: Spring MVC When something goes wrong with your application, the server displays an exception page defining the type of exception, the server-generated exception page is not user-friendly. Spring MVC provides exception handling for your web application to make sure you are sending your own exception page instead of the server-generate
6 min read
Exception Handling in Spring Boot
Exception handling in Spring Boot helps to deal with errors and exceptions present in APIs, delivering a robust enterprise application. This article covers various ways in which exceptions can be handled and how to return meaningful error responses to the client in a Spring Boot Project. Here are some key approaches to exception handling in Spring
8 min read
Different Ways to Prevent Method Overriding in Java
Inheritance is a substantial rule of any Object-Oriented Programming (OOP) language but still, there are ways to prevent method overriding in child classes which are as follows: Methods: Using a static methodUsing private access modifierUsing default access modifierUsing the final keyword method Method 1: Using a static method This is the first way
5 min read
Java - Covariant Method Overriding with Examples
The covariant method overriding approach, implemented in Java 5, helps to remove the client-side typecasting by enabling you to return a subtype of the overridden method's actual return type. Covariant Method overriding means that when overriding a method in the child class, the return type may vary. Before java 5 it was not allowed to override any
4 min read
When We Need to Prevent Method Overriding in Java ?
Here we will be discussing why should we prevent method overriding in java. So, before going into the topic, let's give a look at the below important concept then we will move to the actual topic. As we know Object Oriented Programming (OOPs) concept consists of 4 important concepts that are as follows: EncapsulationInheritancePolymorphismAbstracti
4 min read
Overriding equals method in Java
Consider the following Java program: Java Code class Complex { private double re, im; public Complex(double re, double im) { this.re = re; this.im = im; } } // Driver class to test the Complex class public class Main { public static void main(String[] args) { Complex c1 = new Complex(10, 15); Complex c2 = new Complex(10, 15); if (c1 == c2) { System
3 min read
Overriding toString() Method in Java
Java being object-oriented only deals with classes and objects so do if we do require any computation we use the help of object/s corresponding to the class. It is the most frequent method of Java been used to get a string representation of an object. Now you must be wondering that till now they were not using the same but getting string representa
3 min read
Variables in Java Do Not Follow Polymorphism and Overriding
Variables in Java do not follow polymorphism. Overriding is only applicable to methods but not to variables. In Java, if the child and parent class both have a variable with the same name, Child class's variable hides the parent class's variable, even if their types are different. This concept is known as Variable Hiding. In the case of method over
2 min read
Output of Java program | Set 18 (Overriding)
Prerequisite - Overriding in Java 1) What is the output of the following program? class Derived { protected final void getDetails() { System.out.println("Derived class"); } } public class Test extends Derived { protected final void getDetails() { System.out.println("Test class"); } public static void main(String[] args) { Derive
3 min read
Overriding methods from different packages in Java
Prerequisite : Overriding in Java, Packages in Java Packages provide more layer of encapsulation for classes. Thus, visibility of a method in different packages is different from that in the same package. How JVM find which method to call? When we run a java program, JVM checks the runtime class of the object. JVM checks whether the object's runtim
3 min read
Overriding in Java
In Java, Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. When a method in a subclass has the same name, the same parameters or signature, and the same return type(or sub-type) as a method in its super-class, then th
13 min read
Method Overriding with Access Modifier
Prerequisites: Method Overriding in java and Access Modifier in Java Method Overriding In any object-oriented programming language, Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by its super-class or parent class. When a method in a subclass has the same name,
3 min read
Overriding of Thread class start() method
Whenever we override start() method then our start() method will be executed just like a normal method call and new thread wont be created. We can override start/run method of Thread class because it is not final. But it is not recommended to override start() method, otherwise it ruins multi-threading concept. // Java program illustrate the concept
2 min read
Exception Propagation in Java
Prerequisite : Exceptions in Java, Checked vs Unchecked Exceptions Exception propagation : An exception is first thrown from the top of the stack and if it is not caught, it drops down the call stack to the previous method. After a method throws an exception, the runtime system attempts to find something to handle it. The set of possible "something
3 min read
three90RightbarBannerImg