Reputation: 5319
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?
Upvotes: 1
Views: 980
Reputation:
You can subclass Exception
(instead of RuntimeException
) in those cases.
Upvotes: 0
Reputation: 138882
You should handle as specific Exception
s as possible. If you know when a RuntimeException
may be thrown, you should usually fix your program so it doesn't throw that Exception
.
As far as catching checked Exceptions
go, you should handle as specific an Exception
as you can so:
try {
} catch (FileNotFoundException fnfe){
} catch (IOException ioe){
} catch (Exception e){
}
When you are throwing Exceptions
, you should almost never use throw new Exception()
.
Throw an exception that can give someone who sees it some more information about what happened when it was thrown. (i.e. IndexOutOfBounds
or NullPointerExceptions
. They give specific info w/out even looking at the message or stacktrace.)
If you want to throw an Exception
, and you don't think the Java API has one that fits your case, it is best to subclass or extend the Exception giving it a very informative name.
Upvotes: 2