• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Constructor that throws an Exception

 
Russell Wurth
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is a partial continuation of a previous post regarding my B&S project in which I am using an Object to hold a data record from the database.

I would like to have the constructor of this object throw an Exception if there is a problem with the fields being passed to it, such as:


Is it good practice or style to have constructors throw Exceptions? I am struggling to find an existing Java library that has a constructor that throws an Exception.

Thanks,
Russell Wurth
 
Jon Entwistle
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Russel,

I don't see why not - hava a look a java.io.*, lots of constructors there throw exceptions.

Regards,

Jon
 
Hanna Habashy
Ranch Hand
Posts: 532
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Russell:
I don't see anything wrong for a constructor to throw an exception. I use the same technique all the time to varify the input values.
 
Robert Konigsberg
Ranch Hand
Posts: 172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Like they said at the end of "Die Hard",

Let it throw, let it throw, let it throw!
 
Philippe Maquet
Bartender
Posts: 1872
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Russel,

I think it *can* be a good practice to have a constructor declaring and throwing an exception. But in your example, you're just throwing it in case of an invalid argument, right? And in that case there is the runtime exception IllegalArgumentException (hence which doesn't need to be declared), which looks to fit better.

Regards,

Phil.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic