Tuesday, 17 March 2020

Can a Constructor throw an exception?

Yes, a constructor can throw an exception.

Possible use cases when a constructor throw an exception
a. To design a class with only static methods
If a class has only static methods and you want to restrict object creation of that class, you can throw an exception from the constructor.
package com.smaple.app.utils;

public class ArithemticUtil {

	private ArithemticUtil() throws Exception {
		throw new Exception("Object creation is not supported");
	}

	public static int add(int a, int b) {
		return a + b;
	}

	public static int sub(int a, int b) {
		return a - b;
	}

}

b. When you want to initialize object only if all the underlying resources/objects initialized properly.
package com.sample.app.model;

public class Resource {

	public Resource() {

		try {
			initializeResource1();
			initializeResource2();
		} catch (Exception e) {
			throw e;
		} finally {
			// Close resources
		}
	}

	private void initializeResource1() {

	}

	private void initializeResource2() {

	}
}

For example, When you create an instance of Resource class, it internally create resource1 and resource2. If any of the resource (resource1 or resource2) is not created successfully, then Resource constructor throws an exception and close all the created resources (For Ex: resource1).

You may like

No comments:

Post a Comment