
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
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
Advertisements