Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Exception in constructors: Problematic or not?

I am recently thinking about if throwing constructor from Java is good or not. Currently this is what I gathered:

  1. Can constructors throw exceptions in Java?

    Here, Mr. StackOverflow (aka Jon Skeet) does not seem to hold anything against it, but he did hint about having subclass throwing exceptions. What will happen (anything bad?) when subclass throws exceptions?

  2. http://futuretask.blogspot.com/2006/05/java-tip-10-constructor-exceptions-are.html

    This blog post "Constructor Exceptions are Evil" tells me a way to show that constructor exceptions could be dangerous. However, the example seem to be really esoteric. Is there any real danger here?

  3. I am thinking that if static factory methods (Effective Java 2nd ed., Item 1) are used instead of public constructors, we could safely remove the exceptions from constructors to the static factory method. Is this a valid way to avoid constructor exceptions and is this useful or used in anywhere?

Any inputs are helpful & appreciated. Thanks!

like image 552
zw324 Avatar asked Sep 23 '11 16:09

zw324


1 Answers

There is nothing wrong with exceptions in constructors (or factory methods, either way is fine). sometimes, doing too much work in a constructor can be a poor design, and may make sense to move to a factory method.

the only thing that point 2 proves is that exceptions in constructors are not an adequate security mechanism for protecting a class from evil usage. however, there are any number of ways to subvert such a design, which is why the only way to truly run secure code in java is running with a SecurityManager. so point 2 is just a straw man argument.

like image 199
jtahlborn Avatar answered Oct 16 '22 05:10

jtahlborn