On Throwing Exceptions From Constructors

On Throwing Exceptions From Constructors

It sometimes makes a lot of sense to throw an exceptionfrom the constructor of a class; look at constructors ofthe java.net.URL for an example. But what do we do if we want a subclass that extends a superclass whose constructor throws an exception?Let us exemplify the problem. Suppose we have a class A defined as:

 public class A {    int iValue = 10;    public A(int initValue) throws Exception    {       if(initValue<10)       {          throw new Exception("initial value smaller than 10");        }     } } 

and a subclass of A defined as:

 public class B extends A {    private String iString = null;    public B(int initValue, String initString)    {       super(initValue);       iString = initString;     } } 

Java compiler will not compile B, saying something like:

"Exception java.lang.Exception must be caught, or it must be declared in the throws clause of this constructor" Now, if you try to modify the code for class B to catch the exception on the call to super(...) as in:

 public class B extends A {    private String iString = null;    public B(int initValue, String initString)    {       try       {          super(initValue);       }       catch(Exception e)       {          System.out.println(e.getMessage);       }       iString = initString;     } }

the Java compiler will complain something like:

 "No constructor matching A() found in A" and "Constructor invocation must be the first thing in a method". 

So what do we do? Before answering the question and, thus, providing the solution, let us cover one of the subtleties of object orientation and class hierarchies.

Every instance of class B in our example has an implicitinstance of class A inseparably incorporated within it. In fact, an instance of class B is an implicit instance of class A. In fact, sound hierarchy design follows from generic superclasses whose attributes and behaviors are inherited by their subclasses.

So, If A's constructor throws an exception, it implies that the A instance could not be fully constructed. Therefore, the instance of B within which that instance of A resides cannot be created either.

In other words, not being able to successfully construct our super class implies that we cannot create our derived class?and since constructors are not "overridden", it doesn't make sense that we can override a base class's constructor with different behavior in a derived class. Either we successfully construct each "slice" of our object's inheritance tree, or we don't get an object at all.

Now, the solution: since B is inherently A (we can cast a subclass into its superclass, right?), and A's constructor throws Exception, B's constructor should throw at least the A's Exception. Note that it can throw more exceptions if need be. So, if we define B as:

 public class B extends A {    private String iString = null;    public B(int initValue, String initString) throws Exception    {       super(initValue);       iString = initString;     } } 

If we use this method, the Java compiler will compile our classes successfully.

Share the Post:
Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular

XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several

data fivetran pricing

Fivetran Pricing Explained

One of the biggest trends of the 21st century is the massive surge in analytics. Analytics is the process of utilizing data to drive future decision-making. With so much of

kubernetes logging

Kubernetes Logging: What You Need to Know

Kubernetes from Google is one of the most popular open-source and free container management solutions made to make managing and deploying applications easier. It has a solid architecture that makes