Win a copy of Testing JavaScript Applications this week in the HTML Pages with CSS and JavaScript forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Carey Brown

Java Handeling Exceptions

 
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • 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
  • 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!
 
Just the other day, I was thinking ... about this tiny ad:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
    Bookmark Topic Watch Topic
  • New Topic