3

I am a newbie programmer and I recently started learning about exception handling in Java.

I know what try, catch and finally blocks do, but I really need to understand how to use them well and where to handle something in the call stack...

I have a project right now that involves I/O and all I'm doing is handling the exception in the lowest possible method in the call stack.

I'm sure my exception handling can be improved, so I'm asking you guys how you think of exception handling?

How did you guys get good at this and how can I better wrap my head around this idea?

2

2 Answers 2

4

Uncaught exceptions are for external problem management, caught exceptions for internal

In general, caught exceptions (in your try-catch-finally block) are for problems that your application can do something about. Uncaught, or runtime, exceptions are for problems that are outside the scope of your application to fix by itself (null pointer, database connection failure and so on). Typically a runtime exception is indicating a weakness in your system that an admin or a developer has to address.

When to choose a uncaught exception

Choose a runtime exception when you know that no-one further up the call stack is going to be able to recover without a retry.

"The database connection is borked. This application is not going to be able to restart it since it'll have been provided by JNDI. This application should stop attempting database access right now."

When to choose a caught exception

Choose a caught exception when you know that recovery is possible with a bit of data manipulation from the caller.

"Hey, I got a ParseException, guess I'll add in the time field since it was missing. Should've checked that beforehand..."

Overall, try to stick with the well-defined exceptions already in the language (less code to share around and explain). Understand why they are caught or uncaught. If you absolutely must create your own exception then try to keep the number of variations down and make it helpful in reporting exactly what went wrong. Consider backup up your exception with a detailed log entry if you can.

3
  • 1
    To add, you may want to catch exceptions you cannot fix if you wish to inform the user in some meaningful way.
    – user7007
    Feb 17, 2011 at 20:28
  • caught+caught, no uncaught?
    – user1249
    Feb 18, 2011 at 0:10
  • @Thorbjørn Good spot - word blindness on my part.
    – Gary
    Feb 18, 2011 at 10:13
2

Not a direct answer but a good practice - make sure that when you catch and exception and throw another exception, you pass the original exception as an argument to the new one. Java can maintain useful chains of "caused by", and it's very easy to break those chains by just throwing a completely new exception.

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.