1

Java Runtime Exception is used to check un-checked exception. It is accepted standard that to sub class JavaRunTimeException. Can you please explain me the reason behind sub classing without directly using it as below.

try {
    int x = Integer.parseInt(args[0])/Integer.parseInt(args[0]);
} catch (RuntimeException e) {

}

Recommended approach

public class ServiceFaultException extends RuntimeException {}

try {
    int x = Integer.parseInt(args[0])/Integer.parseInt(args[0]);
} catch (ServiceFaultException e) {

}

I would like to know reasons for this recommendation. ?

1
  • I think you misunderstand the standard. RuntimeException are usually not caught because it could mean anything. That is why you usually catch the subclasses instead (see docs.oracle.com/javase/7/docs/api/java/lang/…). If neither of these matches your exception or error, then it is suggested that you subclass RuntimeException to distinguish one RuntimeException from another. Commented Mar 20, 2014 at 16:47

2 Answers 2

2

Exceptions are used to give some meaning to an error that is not handled right away where it occurs. Subclassing RuntimeException allows you to give more meaning and differentiate between several RuntimeExceptions.

For instance, it is useful to be able to tell the difference between IllegalArgumentException and NumberFormatException, which are both RuntimeExceptions.

EDIT: As @Dyrborg said, catching RuntimeException can also be dangerous because anything could throw it without your knowledge. Better handle only what you control.

ASIDE: You could tell me "why not a checked Exception then ?". I usually use RuntimeExceptions when it corresponds to an incorrect use of a method (illegal argument for instance). It means something the programmer can ensure to avoid. When it comes to user input, or internet connection, which is not reliable, then Exceptions are more appropriate, because the programmer must handle these error cases.

Sign up to request clarification or add additional context in comments.

1 Comment

Obviously, yeah. Except in the very top-top-top-level main, where you might want to show a generic message for a release version of your program, which you don't want to crash.
1

Can you please explain me the reason behind sub classing without directly using it as below.

The same reason as applies to subclassing any other exception. The language provides the facility to catch specific subclasses, so why wouldn't you use it?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.