Can constructors throw exceptions in Java?
Yes, constructors in Java can throw exceptions, just like any other method. If a constructor throws a checked exception, it must be declared in the constructor’s signature using throws
.
For example:
class MyClass {
public MyClass() throws IOException {
// some code that may throw IOException
}
}
This ensures that the calling code handles or declares the exception. Unchecked exceptions (like NullPointerException
) don’t require explicit handling or declaration.