• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
  • Mikalai Zaikin

Java Handeling Exceptions

Posts: 24
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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?
Ranch Hand
Posts: 327
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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!
World domination requires a hollowed out volcano with good submarine access. Tiny ads are optional.
a bit of art, as a gift, the permaculture playing cards
    Bookmark Topic Watch Topic
  • New Topic