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 Advice on handling exceptions Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Advice on handling exceptions" Watch "Advice on handling exceptions" New topic

Advice on handling exceptions

Pho Tek
Ranch Hand

Joined: Nov 05, 2000
Posts: 782

I debugging an existing piece of code which looks like the following.

After start() is called, invocations on method1() and method2() can procede.
If an exception is encountered in start(), conn might end up with the null
value. And method1() and method2() will throw NPEs.

One way to handle the NPE is to: log them & silently default values back.
e.g. I could return the empty Set in method1() and null in method2(). Or perhaps I could throw an IllegalStateException. Which one is better ? Are there other possible alternatives. Thanks
greg buela
Ranch Hand

Joined: Sep 04, 2007
Posts: 71
I would go for the IllegalStateException. A valid connection is a precondition of your methods.
You definitely do not want to just return an empty Set when there is no connection. This can be taken as if there is just no data available at the moment, which could happen with a valid connection.
A client attempting to use these methods without a valid connection might be buggy, so it's better to let it blow up with an exception.

SCJP 1.5
Pho Tek
Ranch Hand

Joined: Nov 05, 2000
Posts: 782

Greg, I'll throw the IllegalStateException like you suggested. Thanks.
I agree. Here's the link:
subject: Advice on handling exceptions
It's not a secret anymore!