Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Method overriding
3.
Exception handling with method overriding
3.1.
When superclass does not declare an exception
3.1.1.
To show that a Subclass can not declare a checked exception
3.1.2.
To show that a Subclass can declare an unchecked exception
3.2.
When the superclass declares an exception
3.2.1.
Case 1: Subclass declares exceptions other than the child exception of the Superclass declared Exception
3.2.2.
Case 2: Subclass declares a child exception of the Superclass declared Exception.
3.2.3.
Case 3: Subclass declares no exception
4.
Frequently Asked Questions 
5.
Key Takeaways
Last Updated: Mar 27, 2024

Exception Handling with Method Overriding in Java

Author Yashesvinee V
0 upvote
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

Exceptions are unexpected events that occur during runtime and cause disruptions in the normal execution of a program. Exceptions and runtime errors are pretty common in programming and can be resolved by Exception handling. Exceptions handling is an error-handling mechanism that maintains the flow of the program and prevents the application from crashing.

A very well known method to handle exceptions in Java is by using the try-catch-finally blocks where the try block identifies an exception and the catch block catches and resolves the exception with an alternative code. Another method of handling exceptions is by rechecking the use of method overriding in classes. Let us first learn what Method Overriding is.

Must Read, Multithreading in java , Duck Number in Java

Method overriding

If a method is present in the superclass and its subclass, then the function in the subclass overrides the one in its superclass. By default, all methods and variables are inherited by a subclass from its superclass. However, if the subclass mentions a method present in the superclass and modifies it, then the instructions present in the subclass method override the original instructions of the superclass, provided it is not declared as final. The main advantage of method overriding is classifying a subclass’s behaviour from its superclass.

Method Overriding is possible only if certain conditions are satisfied. Listed below are a few of them.

  • The argument list of the overridden method must be the same for both the subclass and superclass.
     
  • Constructors and final-declared methods can’t be overridden.
     
  • Only methods that are inherited and not static can be overridden.
     
class Person
{   
   public void hello()
  {
      System.out.println(" Hello Everyone! ");
  }
  public void display()
  {
      System.out.println(" I am a Person ");
  }
}

class Student extends Person
{
  @Override
  public void display()
  {
      System.out.println(" I am a Student ");
  }
}

class Main
{
  public static void main(String[] args)
  {
      Student s1 = new Student();
      s1.hello();
      s1.display();
  }
}

 

Output:

Hello Everyone!
 I am a Student

 

In the above example, the Student class is a subclass of Person, so, it inherits the hello() and display() method. However, the display() method overrides its superclass's display() method; hence, the string ‘I am a Person’ is replaced with ‘I am a Student’. Since there is no overriding function for the hello() method, the code inherited from the superclass is executed.

Also see,  Swap Function in Java

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Exception handling with method overriding

Method overriding, when used to handle exceptions, is quite uncertain as the compiler cannot understand which definition to use, the superclass or subclass. 

There are two important points to remember while handling exceptions using method overriding. 

  • If the superclass method does not declare an exception, then the overriding subclass method cannot declare a checked exception, but it can declare an unchecked exception.
     
  • If the superclass method declares an exception, then the overriding subclass method can declare the same exception, subclass exception or no exception, but it cannot declare a parent exception thrown by the superclass method.
     

Method overriding for exception handling involves two main cases:

  • When a superclass does not declare an exception
     
  • When a superclass declares an exception

When superclass does not declare an exception

To show that a Subclass can not declare a checked exception

class Person
{   
   public void display()
  {
      System.out.println(" I am a Person ");
  }
}

class Student extends Person
{
  @Override
  public void display() throws IOException
  {
      System.out.println(" I am a Student ");
  }
}

class Main
{
  public static void main(String[] args)
  {
      Student s1 = new Student();
      s1.display();
  }
}

 

Output:

error: display() in Student cannot override display() in Person
void display() throws IOException {
    ^
  overridden method does not throw IOException
1 error

 

As shown above, the superclass Person does not throw any exception while the overriding method of subclass Student throws a checked exception.This results in a compilation error as the compiler monitors checked exceptions during compile time. Hence, an overriding subclass method can not throw a checked exception when the overriding superclass method has no exceptions.

To show that a Subclass can declare an unchecked exception

class Person
{   
   public void display() 
   {
      System.out.println(" I am a Person ");
  }
}

class Student extends Person
{
  @Override
  public void display() throws NullPointerException
  {
      System.out.println(" I am a Student ");
  }
}

class Main
{
  public static void main(String[] args)
  {
      Student s1 = new Student();
      s1.display();
  }
}

 

Output:

I am a Student

 

The NullPointerException is an unchecked exception. Although the overridden method has no exceptions, the overriding subclass method can throw an unchecked exception and run successfully.

When the superclass declares an exception

Case 1: Subclass declares exceptions other than the child exception of the Superclass declared Exception

class Person
{ 
  public void display() throws RuntimeException
  {
      System.out.println(" I am a Person ");
  }
}

class Student extends Person
{
  @Override
  public void display() throws Exception
  {
      System.out.println(" I am a Student ");
  }
}

class Main
{
  public static void main(String[] args)
  {
      Student s1 = new Student();
      s1.display();
  }
}

 

Output:

error: display() in Student cannot override display() in Person
void display() throws Exception {
    ^
  overridden method does not throw Exception
1 error

 

The Exception thrown by the subclass overriding method is not a child exception of the RuntimeException, so it throws a compile error. Hence, if the overriding method’s exception is not a child exception of the one thrown by the overridden superclass method, then the code does not compile successfully.

Case 2: Subclass declares a child exception of the Superclass declared Exception.

class Person
{ 
  public void display() throws RuntimeException
  {
      System.out.println(" I am a Person ");
  }
}

class Student extends Person
{
  @Override
  public void display() throws ArithmeticException
  {
      System.out.println(" I am a Student ");
  }
}

class Main
{
  public static void main(String[] args)
  {
      Student s1 = new Student();
      s1.display();
  }
}

 

Output:

I am a Student

 

ArithmeticException is a child exception of RuntimeException, which is thrown by the overridden superclass method. Hence, the compiler does not give any error, and the code executes successfully.

Case 3: Subclass declares no exception

class Person
{ 
  public void display() throws IOException
  {
      System.out.println(" I am a Person ");
  }
}

class Student extends Person
{
  @Override
  public void display()
  {
      System.out.println(" I am a Student ");
  }
}

class Main
{
  public static void main(String[] args)
  {
      Student s1 = new Student();
      s1.display();
  }
}

 

Output:

I am a Student


You can practice by yourself with the help of online java compiler.

The superclass method throws an IOException, while the subclass overriding method does not throw any exception. Similar to the previous case, we get no error on compilation.

Must Read Static Blocks In Java and Hashcode Method in Java

Frequently Asked Questions 

Q: What are the differences between method overriding and method overloading?

  • Method overriding is runtime polymorphism, while method overloading is compile-time polymorphism.
     
  • Parameters, arguments and method signatures need to be the same in method overriding but different in method overloading.
     
  • Final, static or private methods can not be overridden, but they can be overloaded.

 

Q: What are the types of exceptions in Java?

There are two types of exceptions - Checked and unchecked.

  • Checked exceptions are compile-time exceptions that are checked by the compiler. If not handled, we get a compile error. A few examples of checked exceptions are IOException, ClassNotFoundException, InterruptionException, etc.
     
  • Unchecked Exceptions are not checked by the compiler, and do not throw a compile error on ignoring it. Examples of unchecked exceptions are NullPointerException, Arithmetic Exception, etc.

Key Takeaways

Exception Handling is a common way to resolve runtime errors in a program. Hence, one needs to know and understand how to handle various kinds of exceptions in different scenarios. This blog gives an introduction to method overriding and Exception handling. We have also discussed different cases with examples to understand Exceptions in overriding methods. 

Related links:

Checked vs Unchecked Exceptions

Exception Handling with try-catch-finally

Multithreading in Python

Method Overriding in Java

Super Keyword In Java

Java

Check out the official Coding Ninjas Blog site and visit our Library for more.

Previous article
User-defined Custom Exception
Next article
How to solve exception in thread main java.lang.nullpointerexception?
Live masterclass