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?
posted 6 years ago
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!