Home Java Docker
Home     Java

Java Topic

What is Java
History of Java
Freature of Java
Difference Between Java & C++
Java Environment Set Up
Java Hello World Program & its Internal Process
Java Hello World Program
JDK, JRE and JVM
Java Variables
Java Data Types & Unicode System
Java Operators
Java Keywords
Java Control Statements
Java if else
Java switch
Java for loop
Java While loop
Java Do While loop
Java break
Java continue
Java Oops Concept
Java Object & Class
Java Method
Java Constructor
Java Static Keyword
Java this Keyword
Java Inheritance
Java Hybrid Inheritance
Aggregation(HAS-A)
Java Polymorphism
Java method overloading
Java method overriding
Java Runtime polymorphism
Java Dynamic Binding
Super keyword
Final keyword
Difference Between method overloading and method overriding
Java Abstraction
Java Interface
Abstract class vs Interface
Java Encapsulation
Java Package
Java Access Modifiers
covariant return type
Instance initializer block
Java instanceof operator
Object Cloning in Java
Wrapper classes in Java
Java Strictfp Keyword
Recursion in Java
Java Command Line Arguments
Difference between object and class
Java String
Java String Class
Java Immutable String
Java Immutable Class
String Buffer
String Builder
String Buffer vs String
String Builder vs String Buffer
String Tokenizer in Java
Java Array
Java Exceptions Handling
Java Try-Catch block
Java Multiply Catch Block
Java Finally Block
Java Throws Keyword
Java Throw Keyword
Java Exception Propagation
Java Throw vs Throws
Final vs Finally vs Finalize
Exception Handling With Method Overridding
Java Multithreading
Lifecycle and States of a Thread in Java
How to create a thread in Java
Thread Scheduler in Java
Sleeping a thread in Java
Calling run() method
Joining a thread in Java
Naming a thread in Java
Thread Priority
Daemon Thread
Thread Pool
Thread Group
Shutdown hook
Multitasking vs Multithreading
Garbage Collection
RunTime Class
Java Synchronization
Synchronized block in Java
Static Synchronization in Java
Deadlock in Java
Inter Thread Communication in Java
Interrupting Thread in Java
Reentrant Monitor in Java
Java Applet
Animation in Applet
EventHandling in Applet
Display image in Applet
Displaying Graphics in Applet
Parameter in Applet
Java 8 Features
Java Lambda Expressions
Method References
Functional Interfaces
Java 8 Stream
Base64 Encode Decode
Default Method
for Each() Method
Collectors class
String Joiner Class
Optional Class
JavaScript Nashron
Parallel Array Sort
Type Interface
Parameter Reflection
Type and Repeating Annotations
JDBC Improvements

Exception Handling with Method Overriding in Java

  • What is Method Overriding?

    Method overriding is a feature in Java that allows a subclass to provide its own implementation of a method that is already defined in its superclass. By overriding a method, the subclass can customize the behavior of the inherited method according to its specific requirements.

  • Syntax and Rules for Method Overriding in Java

    To override a method in Java, the following syntax and rules must be followed:
    The method in the subclass must have the same name, return type, and parameters as the method in the superclass. The method in the subclass must be declared with the @Override annotation to ensure that it is intended to override a superclass method. The access level of the overriding method in the subclass must be the same or more accessible than the overridden method in the superclass.

  • Importance and Benefits of Method Overriding

    Method overriding plays a crucial role in achieving polymorphism and code reusability in object-oriented programming. It allows subclasses to provide their own specialized behavior while retaining the common interface defined in the superclass. This flexibility enables the creation of more flexible and extensible software systems.
Table Of Content

  • Exception handling with method overriding in Java
  • Example of exception handling with method overriding
  • Second Example of exception handling with method overriding






Exception Handling in Method Overriding


  • Exception Rules for Overriding Methods

    When it comes to exception handling in method overriding, there are certain rules to follow:
    An overriding method is not allowed to throw any checked exceptions that are not declared in the overridden method's exception list. An overriding method can throw any unchecked exception, regardless of whether the overridden method declares it or not. If the overridden method throws a checked exception, the overriding method can choose not to throw any exception or can throw a subtype of the exception declared in the superclass.

  • Checked Exceptions and Overriding Methods

    When dealing with checked exceptions, the overriding method must adhere to the exception handling rules: It can choose not to throw any exception, even if the overridden method declares a checked exception. It can throw the same exception declared in the superclass or its subtype. It is not allowed to throw a new or broader checked exception that is not declared in the overridden method.

  • Unchecked Exceptions and Overriding Methods

    For unchecked exceptions, such as RuntimeExceptions, the overriding method has more flexibility: It can choose not to throw any exception, regardless of whether the overridden method throws an unchecked exception or not. It can throw the same unchecked exception declared in the superclass or its subtype. It can also throw new unchecked exceptions that are not declared in the overridden method.

  • Covariant Return Types and Exception Handling

    In method overriding, it is possible to have covariant return types, where the overriding method returns a subtype of the return type of the overridden method. However, when it comes to exception handling, the same rules still apply. The overriding method must adhere to the exception handling rules mentioned earlier and cannot throw checked exceptions that are not declared in the overridden method.


Best Practices for Exception Handling in Method Overriding


  • Follow the Principle of Least Surprise

    When overriding a method, it is important to maintain consistency with the exception handling behavior of the superclass method. If the superclass method throws certain exceptions, the overriding method should follow the same behavior or throw a subtype of those exceptions.

  • Document Exception Handling Expectations

    Properly document the exceptions that the overriding method may throw. This helps other developers understand the expected exception behavior and handle them accordingly when using the subclass.

  • Use Specific Exception Types Whenever Possible

    When throwing exceptions in an overriding method, it is best to use specific exception types instead of general ones. This provides more precise information about the exceptional condition and allows for better error handling and debugging.

  • Preserve or Rethrow Exceptions Appropriately

    When catching exceptions in an overriding method, carefully consider whether to handle the exception within the method or propagate it further up the call stack. Preserve the original exception context or rethrow it using the throw keyword if necessary.

  • Avoid Swallowing Exceptions

    Avoid catching exceptions in an overriding method without proper handling or logging. Swallowing exceptions can lead to silent failures and make debugging and error resolution challenging.


Exception Handling with Method Overriding

Exception Handling with Method Overriding Where SuperClass does not declare any exception and subclass declare checked exception


package DockerTpoint;
import java.io.*;    
class ParentClass{   
  void message() {  
    System.out.println("parent Class message method");  
    }    
}        
public class Child extends ParentClass{    
    // overriding the method in child class so compile time give error 
  void message() throws IOException {    
    System.out.println("Child Class message method");    
  }  
  
  public static void main(String args[]) {    
    ParentClass parent = new Child ();    
    parent.message();    
  }    
} 





Output:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	Exception IOException is not compatible with throws clause in ParentClass.message()

	at HELLO/DockerTpoint.Child.message(Child.java:11)
	at HELLO/DockerTpoint.Child.child(Child.java:17) 


If Super class doesn't declare any exception


If SubClass declares Unchecked exception and SuperClass does not declare any exception

package DockerTpoint;
import java.io.*;    
class ParentClass{   
  void message() {  
    System.out.println("parent Class message method");  
    }    
}        
public class Child extends ParentClass{    
  void message() throws ArithmeticException{
        // Because ArithmeticException is an Unchecked Exception, the compiler will not generate an error.
        System.out.println("Child Class");
  } 
  public static void main(String args[]) {    
    ParentClass parent = new Child();    
    parent.message();    
  }    
} 



Output:

Child Class 

Example : subclass overridden method declares parent exception


package DockerTpoint;
import java.io.*;    
class ParentClass{   
  void message()throws ArithmeticException {  
    System.out.println("parent Class message method");  
    }    
}        
public class Child extends ParentClass{    
  void message() throws Exception{
        System.out.println("Child Class");
  } 
  public static void main(String args[]) {    
    ParentClass parent = new Child();    
    try {
    	parent.message();    
     } 
     catch (Exception e) {
	 e.printStackTrace();
    }
  }    
}



Output:

 Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	Exception Exception is not compatible with throws clause in ParentClass.message()

	at HELLO/DockerTpoint.Child.message(Child.java:12)
	at HELLO/DockerTpoint.Child.main(Child.java:18)
 


Example : when the same exception is declared by a subclass's overridden method



package DockerTpoint;
import java.io.*;    
class ParentClass{   
  void message()throws Exception {  
    System.out.println("parent Class message method");  
    }    
}        
public class Child extends ParentClass{    
  void message() throws Exception{
        System.out.println("Child Class");
  } 
  public static void main(String args[]) {    
    ParentClass parent = new Child();    
    try {
    	parent.message();    
     } 
     catch (Exception e) {
	 e.printStackTrace();
    }
  }    
}

Output:

Child Class
 

Example : when a method in a subclass is overridden but does not declare an exception



package DockerTpoint;
import java.io.*;    
class ParentClass{   
  void message()  {  
    System.out.println("parent Class message method");  
    }    
}        
public class Child extends ParentClass{    
  void message()  {
        System.out.println("Child Class");
  } 
  public static void main(String args[]) {    
    ParentClass parent = new Child();    
    parent.message();    
  }    
}



Output:

Child Class
 


Example : when a method that is overridden by a subclass declares a subclass exception



package DockerTpoint;
import java.io.*;    
class ParentClass{   
  void message()  {  
    System.out.println("parent Class message method");  
    }    
}        
public class Child extends ParentClass{    
  void message() throws ArithmeticException {
        System.out.println("Child Class");
  } 
  public static void main(String args[]) {    
    ParentClass parent = new Child();    
    try {
    	parent.message();    
     } 
     catch (Exception e) {
	 e.printStackTrace();
    }
  }    
}



Output:

Child Class
 

Custom Exception Next »
« Perv Next »


Post your comment





Read Next Topic
Java Tutorial - Topic
Java Exceptions Handling
Java Try-Catch block
Java Multiply Catch Block
Java Finally Block
Java Throws Keyword
Java Throw Keyword
Java Exception Propagation
Java Throw vs Throws
Final vs Finally vs Finalize
Exception Handling With Method Overridding
custom-exception

Read Other Java Chapter
Java Topic
Java Basic Tutorial
Java Control Statements
Java Classes & Object
Java Inheritance
Java Polymorphism
Java Abstraction
Java Encapsulation
Java OOPs Miscellaneous
Java Array
Java String
Java Exception Handling
Java Multithreading
Java Synchronization
Java Applet
Java 8 Features
Java 9 Features
Java Collection
Java Mcq
Java Interview Question
Tools
  

Useful Links

  • Home
  • Blog
  • About us
  • Contact Us
  • Privacy policy

Contact Us

Police Colony
Patna, Bihar
India

Email:

About DockerTpoint


India's largest site for Programming Tutorial as well as BANK, SSC, RAILWAY exam
and Campus placement preparation.