File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Error or Exception Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Error or Exception" Watch "Error or Exception" New topic

Error or Exception

Ryan Waggoner
Ranch Hand

Joined: Jun 27, 2007
Posts: 75
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

Joined: May 26, 2003
Posts: 33102

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.

[OCA 8 book] [Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Other Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, TOGAF part 1 and part 2
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
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.

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
I agree. Here's the link:
subject: Error or Exception
It's not a secret anymore!