Can we throw exception in constructor java

Can Constructor Throw Exceptions in Java?

In Java, methods can throw exceptions. Can constructors also throw exceptions? The answer is YES.

2. The reason and some necessary background

A constructor is just a special method. In this perspective, it surely can do what regular methods can do.

It is possible that there are some objects created and assigned to static fields before the constructor method is done. In this case, the object that should be created is not created yet. So you need to be careful about the consistency.

Here is an example constructor method that throws an exception.

class FileReader{ public FileInputStream fis = null; public FileReader() throws IOException{ File dir = new File(".");//get current directory File fin = new File(dir.getCanonicalPath() + File.separator + "not-existing-file.txt"); fis = new FileInputStream(fin); } }

If you want to know the best practice of Java exception handling, I highly recommend this post.

If you want someone to read your code, please put the code inside

 and 

tags. For example:

Источник

Throwing Exceptions in Constructors

announcement - icon

As always, the writeup is super practical and based on a simple application that can work with documents with a mix of encrypted and unencrypted fields.

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

Читайте также:  Где запустить код javascript

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

> CHECK OUT THE COURSE

1. Overview

Exceptions provide separation of error handling code from the normal flow of the application. It’s not uncommon to throw an exception during the instantiation of an object.

In this article, we’ll examine all the details about throwing exceptions in constructors.

2. Throwing Exceptions in Constructors

Constructors are special types of methods invoked to create an object. In the following sections, we’ll look into how to throw exceptions, which exceptions to throw, and why we would throw exceptions in constructors.

2.1. How?

Throwing exceptions in the constructor is no different from doing so in any other method. Let’s start by creating an Animal class with a no-arg constructor:

public Animal() throws InstantiationException

Here, we’re throwing InstantiationException, which is a checked exception.

2.2. Which Ones?

Even though throwing any type of exception is allowed, let’s establish some best practices.

First, we don’t want to throw “java.lang.Exception”. This is because the caller cannot possibly identify what kind of exception and thereby handle it.

Second, we should throw a checked exception if the caller has to forcibly handle it.

Third, we should throw an unchecked exception if a caller cannot recover from the exception.

It’s important to note that these practices are equally applicable for both methods and constructors.

2.3. Why?

In this section, let’s understand why we might want to throw exceptions in the constructor.

Argument validation is a common use case for throwing exceptions in the constructor. Constructors are mostly used to assign values of variables. If the arguments passed to the constructor are invalid, we can throw exceptions. Let’s consider a quick example:

public Animal(String id, int age)

In the above example, we’re performing argument validation before initializing the object. This helps to ensure that we’re creating only valid objects.

Here, if the id passed to the Animal object is null, we can throw NullPointerException For arguments that are non-null but still invalid, such as a negative value for age, we can throw an IllegalArgumentException.

Security checks are another common use case for throwing exceptions in the constructor. Some of the objects need security checks during their creation. We can throw exceptions if the constructor performs a possibly unsafe or sensitive operation.

Let’s consider our Animal class is loading attributes from a user input file:

public Animal(File file) throws SecurityException, IOException < if (file.isAbsolute()) < throw new SecurityException("Traversal attempt"); >if (!file.getCanonicalPath() .equals(file.getAbsolutePath())) < throw new SecurityException("Traversal attempt"); >> 

In our example above, we prevented the Path Traversal attack. This is achieved by not allowing absolute paths and directory traversal. For example, consider file “a/../b.txt”. Here, the canonical path and the absolute path are different, which can be a potential Directory Traversal attack.

3. Inherited Exceptions in Constructors

Now, let’s talk about handling superclass exceptions in constructors.

Читайте также:  Php imagick html to image

Let’s create a child class, Bird, that extends our Animal class:

public class Bird extends Animal < public Bird() throws ReflectiveOperationException < super(); >public Bird(String id, int age) < super(id, age); >>

Since super() has to be the first line in the constructor, we can’t simply insert a try-catch block to handle the checked exception thrown by the superclass.

Since our parent class Animal throws the checked exception InstantiationException, we can’t handle the exception in the Bird constructor. Instead, we can propagate the same exception or its parent exception.

It’s important to note that the rule for exception handling with respect to method overriding is different. In method overriding, if the superclass method declares an exception, the subclass overridden method can declare the same, subclass exception, or no exception, but cannot declare a parent exception.

On the other hand, unchecked exceptions need not be declared, nor can they be handled inside subclass constructors.

4. Security Concerns

Throwing an exception in a constructor can lead to partially initialized objects. As described in Guideline 7.3 of Java Secure Coding Guidelines, partially initialized objects of a non-final class are prone to a security concern known as a Finalizer Attack.

In short, a Finalizer attack is induced by subclassing partially initialized objects and overriding its finalize() method, and attempts to create a new instance of that subclass. This will possibly bypass the security checks done inside the constructor of the subclass.

Overriding the finalize() method and marking it final can prevent this attack.

However, the finalize() method has been deprecated in Java 9, thus preventing this type of attack.

5. Conclusion

In this tutorial, we’ve learned about throwing exceptions in constructors, along with the associated benefits and security concerns. Also, we took a look at some best practices for throwing exceptions in constructors.

As always, the source code used in this tutorial is available over on GitHub.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

Can a constructor throw an exception in Java?

Yes, constructors are allowed to throw an exception in Java.

A Constructor is a special type of a method that is used to initialize the object and it is used to create an object of a class using the new keyword, where an object is also known as an Instance of a class. Each object of a class will have its own state (Instance variables) and access to methods of its class.

Throw an Exception from a Constructor

  • A checked exception can be used to indicate a legitimate problem when trying to create an instance, while an unchecked exception typically indicates a bug either in the client code or in the constructor itself.
  • In both cases, an object is actually allocated in the heap space, but a reference to it is not returned. The object remains in a partially initialized state until it gets garbage collected.so we conclude that saving a reference to the object from the constructor itself (by using this reference) is a risky thing, since we may give access to an object in an invalid state.
  • Another important thing to note about the exception in a constructor is related to reflection. When we need to invoke the empty constructor using a class object for example test, we sometimes use the method test.newInstance().
  • Any exception thrown by the constructors is propagated without a change. In other words, the newInstance() method may throw checked exception that it does not even declare.
Читайте также:  Automated software testing with python

Example

public class ConstructorExceptionTest < public ConstructorExceptionTest() throws InterruptedException < System.out.println("Preparing an Object"); Thread.sleep(1000); System.out.println("Object is ready"); >public static void main(String args[]) < try < ConstructorExceptionTest test = new ConstructorExceptionTest(); >catch (InterruptedException e) < System.out.println("Got interrupted. "); >> >

Output

Preparing an Object Object is ready

Источник

Can constructor throw exceptions in Java?

A constructor is used to initialize an object when it is created. It is syntactically similar to a method. The difference is that the constructors have same name as their class and, have no return type.

There is no need to invoke constructors explicitly these are automatically invoked at the time of instantiation.

Example

public class Example < public Example()< System.out.println("This is the constructor of the class example"); >public static void main(String args[]) < Example obj = new Example(); >>

Output

This is the constructor of the class example

Constructor throwing exceptions

Yes, just like methods you can throw exceptions from constructors in. But, if you do so, you need to catch/throw (handle) the exception at the method where you invoke the constructor. If you don’t a compile time error is generated.

Example

In the following example we have a class named Employee whose constructor throws an IOException, we are instantiating this class without handling the exception. Therefore, if you compile this program, it generates a compile time error.

import java.io.File; import java.io.FileWriter; import java.io.IOException; class Employee < private String name; private int age; File empFile; Employee(String name, int age, String empFile) throws IOException< this.name = name; this.age = age; this.empFile = new File(empFile); new FileWriter(empFile).write("Employee name is "+name+"and age is "+age); >public void display() < System.out.println("Name: "+name); System.out.println("Age: "+age); >> public class ConstructorExample < public static void main(String args[]) < String filePath = "samplefile.txt"; Employee emp = new Employee("Krishna", 25, filePath); >>

Compile time error

ConstructorExample.java:23: error: unreported exception IOException; must be caught or declared to be thrown Employee emp = new Employee("Krishna", 25, filePath); ^ 1 error

Example

To make this program work properly, wrap the instantiation line within try-catch or, throw the exception.

import java.io.File; import java.io.FileWriter; import java.io.IOException; class Employee < private String name; private int age; File empFile; Employee(String name, int age, String empFile) throws IOException< this.name = name; this.age = age; this.empFile = new File(empFile); new FileWriter(empFile).write("Employee name is "+name+"and age is "+age); >public void display() < System.out.println("Name: "+name); System.out.println("Age: "+age); >> public class ConstructorExample < public static void main(String args[]) < String filePath = "samplefile.txt"; Employee emp = null; try < emp = new Employee("Krishna", 25, filePath); >catch(IOException ex) < System.out.println("Specified file not found"); >emp.display(); > >

Output

Источник

Оцените статью