Difference between java.lang.RuntimeException and

2019-01-01 14:34发布

问题:

Someone please explain the difference between java.lang.RuntimeException and java.lang.Exception? How do I decide which one to extend if I create my own exception?

回答1:

Generally RuntimeExceptions are exceptions that can be prevented programmatically. E.g NullPointerException, ArrayIndexOutOfBoundException. If you check for null before calling any method, NullPointerException would never occur. Similarly ArrayIndexOutOfBoundException would never occur if you check the index first. RuntimeException are not checked by the compiler, so it is clean code.

EDIT : These days people favor RuntimeException because the clean code it produces. It is totally a personal choice.



回答2:

In Java, there are two types of exceptions: checked exceptions and un-checked exceptions. A checked exception must be handled explicitly by the code, whereas, an un-checked exception does not need to be explicitly handled.

For checked exceptions, you either have to put a try/catch block around the code that could potentially throw the exception, or add a \"throws\" clause to the method, to indicate that the method might throw this type of exception (which must be handled in the calling class or above).

Any exception that derives from \"Exception\" is a checked exception, whereas a class that derives from RuntimeException is un-checked. RuntimeExceptions do not need to be explicitly handled by the calling code.



回答3:

Before looking at the difference between java.lang.RuntimeException and java.lang.Exception classes, you must know the Exception hierarchy. Both Exception and Error classes are derived from class Throwable (which derives from the class Object). And the class RuntimeException is derived from class Exception.

All the exceptions are derived either from Exception or RuntimeException.

All the exceptions which derive from RuntimeException are referred to as unchecked exceptions. And all the other exceptions are checked exceptions. A checked exception must be caught somewhere in your code, otherwise, it will not compile. That is why they are called checked exceptions. On the other hand, with unchecked exceptions, the calling method is under no obligation to handle or declare it.

Therefore all the exceptions which compiler forces you to handle are directly derived from java.lang.Exception and all the other which compiler does not force you to handle are derived from java.lang.RuntimeException.

Following are some of the direct known subclasses of RuntimeException.

AnnotationTypeMismatchException,
ArithmeticException,
ArrayStoreException,
BufferOverflowException,
BufferUnderflowException,
CannotRedoException,
CannotUndoException,
ClassCastException,
CMMException,
ConcurrentModificationException,
DataBindingException,
DOMException,
EmptyStackException,
EnumConstantNotPresentException,
EventException,
IllegalArgumentException,
IllegalMonitorStateException,
IllegalPathStateException,
IllegalStateException,
ImagingOpException,
IncompleteAnnotationException,
IndexOutOfBoundsException,
JMRuntimeException,
LSException,
MalformedParameterizedTypeException,
MirroredTypeException,
MirroredTypesException,
MissingResourceException,
NegativeArraySizeException,
NoSuchElementException,
NoSuchMechanismException,
NullPointerException,
ProfileDataException,
ProviderException,
RasterFormatException,
RejectedExecutionException,
SecurityException,
SystemException,
TypeConstraintException,
TypeNotPresentException,
UndeclaredThrowableException,
UnknownAnnotationValueException,
UnknownElementException,
UnknownTypeException,
UnmodifiableSetException,
UnsupportedOperationException,
WebServiceException 


回答4:

An Exception is checked, and a RuntimeException is unchecked.

Checked means that the compiler requires that you handle the exception in a catch, or declare your method as throwing it (or one of its superclasses).

Generally, throw a checked exception if the caller of the API is expected to handle the exception, and an unchecked exception if it is something the caller would not normally be able to handle, such as an error with one of the parameters, i.e. a programming mistake.



回答5:

The runtime exception classes (RuntimeException and its subclasses) are exempted from compile-time checking, since the compiler cannot establish that run-time exceptions cannot occur. (from JLS).

In the classes that you design you should subclass Exception and throw instances of it to signal any exceptional scenarios. Doing so you will be explicitly signaling the clients of your class that usage of your class might throw exception and they have to take steps to handle those exceptional scenarios.

Below code snippets explain this point:

//Create your own exception class subclassing from Exception
class MyException extends Exception {
    public MyException(final String message) {
        super(message);
    }
}

public class Process {
    public void execute() {
        throw new RuntimeException(\"Runtime\");
    }  
    public void process() throws MyException {
        throw new MyException(\"Checked\");
    }
}

In the above class definition of class Process, the method execute can throw a RuntimeException but the method declaration need not specify that it throws RuntimeException.

The method process throws a checked exception and it should declare that it will throw a checked exception of kind MyException and not doing so will be a compile error.

The above class definition will affect the code that uses Process class as well.

The call new Process().execute() is a valid invocation where as the call of form new Process().process() gives a compile error. This is because the client code should take steps to handle MyException (say call to process() can be enclosed in a try/catch block).



回答6:

Proper use of RuntimeException?

From Unchecked Exceptions -- The Controversy:

If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.

Note that an unchecked exception is one derived from RuntimeException and a checked exception is one derived from Exception.

Why throw a RuntimeException if a client cannot do anything to recover from the exception? The article explains:

Runtime exceptions represent problems that are the result of a programming problem, and as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way. Such problems include arithmetic exceptions, such as dividing by zero; pointer exceptions, such as trying to access an object through a null reference; and indexing exceptions, such as attempting to access an array element through an index that is too large or too small.



回答7:

From oracle documentation:

Here\'s the bottom line guideline: If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.

Runtime exceptions represent problems that are the result of a programming problem and as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way.

RuntimeExceptions are like \"exceptions by invalid use of an api\" examples of runtimeexceptions: IllegalStateException, NegativeArraySizeException, NullpointerException

With the Exceptions you must catch it explicitly because you can still do something to recover. Examples of Exceptions are: IOException, TimeoutException, PrintException...



回答8:

In simple words, if your client/user can recover from the Exception then make it a Checked Exception, if your client can\'t do anything to recover from the Exception then make it Unchecked RuntimeException. E.g, a RuntimeException would be a programmatic error, like division by zero, no user can do anything about it but the programmer himself, then it is a RuntimeException.



回答9:

RuntimeException is a child class of Exception class

This is one of the many child classes of Exception class. RuntimeException is the superclass of those exceptions that can be thrown during the normal operation of the Java Virtual Machine. A method is not required to declare in its throws clause any subclasses of RuntimeException that might be thrown during the execution of the method but not caught.

The hierchy is

java.lang.Object

---java.lang.Throwable

-------java.lang.Exception

-------------java.lang.RuntimeException



回答10:

Exceptions are a good way to handle unexpected events in your application flow. RuntimeException are unchecked by the Compiler but you may prefer to use Exceptions that extend Exception Class to control the behaviour of your api clients as they are required to catch errors for them to compile. Also forms good documentation.

If want to achieve clean interface use inheritance to subclass the different types of exception your application has and then expose the parent exception.



回答11:

There are two types of exception, You can recover from checked exception if you get such kind of exception. Runtime exception are irrecoverable, runtime exceptions are programming errors, and programmer should take care of it while writing the code, and continue execution of this might give you incorrect result. Runtime exceptions are about violating precondition ex. you have an array of size 10, and you are trying to access 11 th element, it will throw ArrayIndexOutOfBoundException



回答12:

  1. User-defined Exception can be Checked Exception or Unchecked Exception, It depends on the class it is extending to.

  2. User-defined Exception can be Custom Checked Exception, if it is extending to Exception class

  3. User-defined Exception can be Custom Unchecked Exception , if it is extending to Run time Exception class.

  4. Define a class and make it a child to Exception or Run time Exception