• Post Reply Bookmark Topic Watch Topic
  • New Topic

Exception Handling in a Constructer  RSS feed

 
Akhilesh Murthy
Ranch Hand
Posts: 31
1
Java Oracle Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

Is there a special mechanism through which exception can be handled in a constructor?

Suppose while creation of an object there occurred an exception while creating an object, and the object is half constructed. How do we make sure we handle this kind of exceptions in a constructor?

 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, there is no special mechanism to handle exceptions in a constructor; it's not necessary to have a special mechanism. It works just like exceptions in methods. When a constructor throws an exception, then at the place where the object was created with the "new" operator, the exception happens, and no object is returned.
 
Mike. J. Thompson
Bartender
Posts: 689
17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are no special mechanisms for handling Exceptions in a constructor. You have the same 2 choices you have everywhere else. Either you have a try/catch in the constructor, or you throw the Exception from the constructor.

Note that if a constructor throws an Exception it will not produce a partially constructed object. The reference you were assigning to will be null.
 
Tushar Goel
Ranch Hand
Posts: 934
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Jasper and Mike, i was not aware of that 'constructor can also throw exception as well'. I always tried to use try/catch.
 
Campbell Ritchie
Marshal
Posts: 56578
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Whenever you have an Exception, don't go thinking, “How do I get a try‑catch here?”
What you want is, “How can I correct the problem here?”new Foo(-123)
How could you sort out that negative number? Would you supply a default, or change its sign? What about this?
new Foo(-2147483648)
You can't turn that positive. So you decide you cannot sort out that error in the constructor. Throwing the Exception means, “I have a problem and I cannot sort it out here. I shall have to pass it back to whoever called this constructor or method and they will have to correct it.”
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!