Java - Exception Handling With Constructors in Inheritance
Last Updated :
15 Nov, 2021
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 exception or its parent classes. There is no problem if the parent class or child class constructor throws any unchecked exceptions. The child class constructor can throw any unchecked exception without looking for a parent class constructor.
Understanding behavior of constructor calls
Whenever a method that throws some exception is called by another method, then the calling method is responsible for handling that exception (The calling method is the method that contains the actual call; the called method is the method being called). In case of constructors, the parent class constructor is called by the child class constructor. It means the child class constructor is responsible for handling the exception thrown by the parent class constructor.
Now, for handling an exception there are two ways, one is to catch the exception and another is to throw it. But in the case of the constructor, we can't handle it using the try-catch mechanism. The reason is that we enclose our code which can raise an exception in the try block and then catch it. The exception is raised due to a call to parent class constructor, like super(). It means if we want to handle the exception using try-catch is depicted in the below illustration.
Illustration 1
Child() {
// Try- catch block
try
{
super();
}
catch (FileNotFoundException exc)
{
// Handling exception(code)
}
}
Actually, it is not correct as a call to super must be first statement in the child class constructor (refer super in java as it can be perceived from below illustration as follows:
Illustration 2
Child() {
super(); // either called explicitly or added by the compiler in case of default constructor
try {
// your code
}
catch(FileNotFoundException exc) {
// handling code;
}
}
and hence the exception can't be caught (as its not inside the try block) and we can't handle it using try-catch mechanism. That's why we need to throw the exception. The below code will compile fine which will appear as follows:
// parent class constructor throws FileNotFoundException
Child() throws FileNotFoundException {
super(); // either called explicitly or added by the compiler in case of default constructor
try {
// your code
}
catch(FileNotFoundException exc) {
// handling code;
}
}
Different Use-cases:
- Parent class constructor does not throw any checked exception
- Parent class constructor throws a checked exception
Now let us discuss each case in detail alongside justifying via clean java programs.
Case 1: Parent class constructor does not throw any checked exception
If the parent class constructor does not throw any exception then the child class can throw any exception or throw nothing.
Example 1
Java
// Java Program to Illustrate Exception handling with
// Constructors in inheritance where Parent class
// constructor does not throw any checked exception
// Class 1
// Parent class
class Parent {
// Constructor of Parent class
// Not throwing any checked exception
Parent()
{
// Print statement whenever parent class
// constructor is called
System.out.println("parent class constructor");
}
}
// Class 2
// Child class
public class Child extends Parent {
// Constructor of child class
Child()
{
// Print statement whenever child class
// constructor is called
System.out.println("child class constructor");
}
// main driver method
public static void main(String[] args)
{
// Creating object of child class inside main()
Child child = new Child();
}
}
Outputparent class constructor
child class constructor
Example 2
Java
// Java Program to Illustrate Exception handling with
// Constructors in inheritance where Parent class
// constructor does not throw any checked exception
// Class 1
// Parent class
class Parent {
// Constructor of parent class
// Not throwing any checked exception
Parent()
{
// Print statement when constructor of
// parent class is called
System.out.println("parent class constructor");
}
}
// Class 2
// Child class
public class Child extends Parent {
Child() throws Exception
{
// Print statement when constructor of
// child class is called
System.out.println(
"child class constructor throwing Exception");
}
// Main driver method
public static void main(String[] args) throws Exception
{
// Creating object of child class
Child child = new Child();
}
}
Outputparent class constructor
child class constructor throwing Exception
Case 2: Parent class constructor throws a checked exception
If the parent class constructor throws a checked exception, then the child class constructor can throw the same exception or its super-class exception. Now at this point, the child class constructors have to throw the exception.
Example
Java
// Java Program to Illustrate Exception handling with
// Constructors in inheritance where Child class constructor
// Not throwing exception of same type or its parent classes
// Importing I/O classes
import java.io.*;
// Class 1
// Parent class
class Parent {
// Constructor of parent class
// Throwing checked exception
Parent() throws FileNotFoundException
{
// Print statement when
// parent class constructor is called
System.out.println(
"parent class constructor throwing exception");
}
}
// Class 2
// Child class
class Child extends Parent {
// Constructor of child class
Child()
{
// Print statement when
// child class constructor is called
System.out.println("child class constructor");
}
// Main driver method
public static void main(String[] args) throws Exception
{
// Creating object of child class inside main()
Child child = new Child();
}
}
Output
error: unreported exception FileNotFoundException; must be caught or declared to be thrown
Child() {
^
In order to resolve the error we need to declare the exceptions to be thrown. These exception can be of same or parent class.
Example 1
Java
// Java Program to Illustrate Exception handling with Constructors
// in Inheritance where we Resolve the Error we Need to
// Declare the Exceptions to be Thrown
// Importing I/O classes
import java.io.*;
// Parent class
class Parent {
// throwing checked exception
Parent() throws FileNotFoundException {
System.out.println("parent class constructor throwing checked exception");
}
}
public class Child extends Parent {
Child() throws FileNotFoundException {
System.out.println("child class constructor throwing same exception");
}
public static void main(String[] args) throws Exception {
Child child = new Child();
}
}
Output
parent class constructor throwing checked exception
child class constructor throwing same exception
Example 2
Java
// Java Program to Illustrate Exception handling with
// Constructors in Inheritance where we Resolve the Error we
// Need to Declare the Exceptions to be Thrown
// Importing I/O classes
// Importing package
package package1;
// Importing required I/O classes
import java.io.*;
// Class 1
// Parent class
class Parent {
// throwing checked exception
Parent() throws FileNotFoundException
{
System.out.println(
"parent class constructor throwing checked exception");
}
}
// Class 2
// Child class
public class Child extends Parent {
// It can also throw same exception or its parent
// classes exceptions
Child() throws IOException
{
System.out.println(
"child class constructor throwing super-class exception");
}
// Main driver method
public static void main(String[] args) throws Exception
{
// Creating object of child class
// inside main() method
Child child = new Child();
}
}
Output
parent class constructor throwing checked exception
child class constructor throwing super-class exception
Similar Reads
Inheritance and Constructors in Java
Constructors in Java are used to initialize the values of the attributes of the object serving the goal to bring Java closer to the real world. We already have a default constructor that is called automatically if no constructor is found in the code. But if we make any constructor say parameterized
3 min read
Nested try blocks in Exception Handling in Java
In Java, we can use a try block within another try block. This is called nested try blocks. Each time a try statement is entered, the context of that exception is pushed onto a stack. If an exception occurs in the inner try block and is not caught by its corresponding catch block, the exception prop
4 min read
Favoring Composition Over Inheritance In Java With Examples
In object-oriented programming (OOP), choosing between inheritance and composition is crucial for designing flexible and maintainable code. This article explores why you should favor composition over inheritance, with simple explanations and examples.What is Inheritance?Inheritance is when a new cla
4 min read
Why Constructors are not inherited in Java?
Constructor is a block of code that allows you to create an object of class and has same name as class with no explicit return type. Whenever a class (child class) extends another class (parent class), the sub class inherits state and behavior in the form of variables and methods from its super clas
2 min read
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.W
4 min read
Generic Constructors and Interfaces in Java
Generics make a class, interface and, method, consider all (reference) types that are given dynamically as parameters. This ensures type safety. Generic class parameters are specified in angle brackets â<>â after the class name as of the instance variable. Generic constructors are the same as
5 min read
Constructor newInstance() method in Java with Examples
The newInstance() method of a Constructor class is used to create and initialize a new instance of this constructor, with the initialization parameters passed as parameter to this method. Each parameter is unwrapped to match primitive formal parameters, and both primitive and reference parameters ar
3 min read
Exception Handling in Spring Boot
Exception handling in Spring Boot helps 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. Key Approaches
8 min read
Using final with Inheritance in Java
Prerequisite - Overriding in java, Inheritance final is a keyword in java used for restricting some functionalities. We can declare variables, methods, and classes with the final keyword. Using final with inheritance During inheritance, we must declare methods with the final keyword for which we are
4 min read
CloneNotSupportedException in Java with Examples
CloneNotSupportedException is thrown to show that the clone method in class Object has been called to clone an object, but that the object's class does not implement the Cloneable interface. Hierarchy: Those applications which override the clone method can also throw this type of exception to indica
1 min read