Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

How to handle exceptions in constructor?  RSS feed

 
George Lin
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello everyone,


When exceptions occur in constructor so that the instance of the object can not be created, should we throw the exception to the invoker of the constructor or simply catch the exception (and not throw it again)?

I think we should not catch the exception (and not throw it again), since in this approach, the invoker can not see whether the instance of the object has been created successfully.

I think we should throw the exception to let the invoker know that the instance of the object has not been created successfully, so that the invoker can peform appropriate actions. But I am not quite sure whether I am correct since I have not seen any constructors which throw exceptions before.

Could anyone help?


Thanks in advance,
George
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, you're absolutely right. If a constructor has a problem which prevents it from completing properly, it should indeed throw an exception. There are plenty of examples of this in the Java APIs. The first one that pops into my mind is java.net.URL. If you try to construct one with invalid data, you'll get a MalformedURLException. That way you know for sure that every URL object represents a syntactically correct URL.
 
George Lin
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Ernest,


Originally posted by Ernest Friedman-Hill:
Yes, you're absolutely right. If a constructor has a problem which prevents it from completing properly, it should indeed throw an exception. There are plenty of examples of this in the Java APIs. The first one that pops into my mind is java.net.URL. If you try to construct one with invalid data, you'll get a MalformedURLException. That way you know for sure that every URL object represents a syntactically correct URL.


Your reply is very helpful.


regards,
George
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!