Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Error or Exception

 
Ryan Waggoner
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I couldn't figure out which to do with my methods.
Should I use a try/catch and throw an error, or have my method throw an exception?
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34410
346
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ryan,
What should happen if the exception case occurs. Is it fatal? Then you should throw an exception. Or can you handle it? Then you should catch it and take appropriate action.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I use two guidelines that give different answers in a bit of a balancing act:

Jeanne covered the first one: If you can't do anything with the exception, like retry the operation another way or do something else instead, just let it bubble up to the calling method. Don't code "catch, log, throw" unless you really add some value.

But! Don't expose your inner workings in the type of exception. For example if I have a data access interface that might be implemented with a database or flat files or calls to a remote partner system, I don't want the database version to throw SQLExceptions. I'd invent my own DataAccessException, catch any SQL or IO or whatever exceptions and throw only DataAccessException. That way the caller never needs to know whether I'm using a database or something else.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic