It's not a secret anymore!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Java Handeling Exceptions Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Java Handeling Exceptions" Watch "Java Handeling Exceptions" New topic

Java Handeling Exceptions

Lennie De Villiers

Joined: Jul 17, 2009
Posts: 24
Hi, I'm studying for Java Programmer Certification (SCJP) exam. A question about exceptions, when handle exceptions is it best to handle a specific exception like NumberFormatException or catch all exceptions use the parent Exception class?

Base on my course unchecked exceptions are basically a RunTimeException which mostly result of a program bug. Does this mean that when I throw an exception manually I should rather use:

new Exception("... my message...")
and that I shouldn't handle RunTimeException? Only handle checked exceptions?
Jason Irwin
Ranch Hand

Joined: Jun 09, 2009
Posts: 327
You are forced to handle checked exceptions by Java, either with a "catch" or with a "throws" in the method declaration.

As to handling specific exceptions, that really depends on your design and what your code is doing. It may be possible to recover form some exceptions, others may mean your code has to do some clean up and so on. For example...say your code takes some user input. You check that input and throw an "IllegalArgumentException" if it does not pass some validation. A way to recover from this would be to trap that specific exception and simply ask the user for the input again after stating what the fault was.

An other example could be file access. If the file is locked by another process you may want your code to wait for a second before trying again, and to repeat this some number of defined times before giving up.

Other exceptions (such as StackOverflow or OutOfMemory) there is nothing you can do to recover from and your only hope is to exit as gracefully as possible.

If you are going to throw an exception, you should make it as specific to the problem you detected as possible. 'throw new Exception("...");' is a good way to really upset your colleagues!

I agree. Here's the link:
subject: Java Handeling Exceptions
It's not a secret anymore!