In the exceptions hierarchy, the descendants of
RuntimeException and those of Error are runtime exceptions/errors.
The difference between the two is: Those under RuntimeException are
the ones caused by poor programming/design, and those of Error are
the ones that can't/shouldn't be controlled by the developer.
For coding an exception within the application,
for instance, to throw an exception when something in the business logic occurs,
the RuntimeException is extended.
The question is, what exactly is the difference between extending
RuntimeException and extending Error-- except that extending
Error is bad practice?
Both Error and RuntimeException are unchecked exceptions, meaning that it indicate a flaw with the program, and usually should not be caught. (NullPointerException, IndexOutOfBoundsException, etc.)
I think the main difference between the two is that RuntimeException indicate there is a error with the program, and an Error is something that is fatal but out of the program's control. (OutOfMemorryError, ThreadDeath, etc.)
Therefore subclassing an Error is bad practice because an error is usually not something that could be fixed by your program at runtime. In your program, should you need to throw something, use an Exception.
The Q is, what exactly is the difference between extending
RuntimeException and extending Error-- except that extending Error is
bad practice?
You've already mentioned the main differences. The Java Language Specification says the same thing in different terms. For Error, it states
Error is the superclass of all the exceptions from which ordinary
programs are not ordinarily expected to recover.
For RuntimeException, it states
The class RuntimeException is a direct subclass of Exception.
RuntimeException is the superclass of all the exceptions which may be
thrown for many reasons during expression evaluation, but from which
recovery may still be possible.
What you should take away from these quotes is that you will commonly see
try {
...
} catch (Exception e) { // catches RuntimeException
...
}
as a catch all case since Exception is a super type of RuntimeException. But you will almost never see (I've never seen it)
try {
...
} catch (Error e) {
...
}
We have Throwable class which is the base class for Error class (for unrecoverable errors) and Exception class(for recoverable errors)
So,
1> we can throw an object that implement error class.(Although it doesn't make sense to implement Error class because we have Exception class to do the same thing..)
2> Java doesn't recommend to catch Error object..
So what is the need of Error object then? Cant the compiler implement it internally? Isn't it a mistake?
Technically, the distinction is not really made between "unrecoverable error" and "recoverable error", but between checked exceptions and unchecked exceptions. Java does distinguish between them as follows:
you must declare a checked exception in your throws clause; if using a method which throws a checked exception in a try block, you must either catch said exception or add this exception to your method's throws clause;
you may declare an unchecked exception in your throws clause (not recommended); if using a method which throws an unchecked exception in a try block, you may catch that exception or add this exception to your method's throws clause (not recommended either).
What is certainly not recommended, unless you really know what you are doing, is to "swallow" any kind of unchecked exception (ie, catch it with an empty block).
Exception is the base checked exception class; Error and RuntimeException are both unchecked exceptions, and so are all their subclasses. You will note that all three classes extend Throwable, and the javadoc for Throwable states that:
For the purposes of compile-time checking of exceptions, Throwable and
any subclass of Throwable that is not also a subclass of either
RuntimeException or Error are regarded as checked exceptions.
Classical examples of (in)famous unchecked exceptions:
OutOfMemoryError (extends Error);
StackOverflowError (extends Error);
NullPointerException (extends RuntimeException);
IllegalArgumentException (extends RuntimeException);
etc etc.
The only real difference between Error and RuntimeException is their estimated severity level, and is a "semantic" difference, not a technical difference: ultimately, both behave the same. Some IDEs (Intellij IDEA comes to mind) will also yell at you if you catch an Error but do not rethrow it.
You certainly can throw objects that extend (not implement) the Error class.
As you said, Error exists for unrecoverable errors. The most extensive use is within the JVM itself which uses subclasses of Error for things it can't recover from and doesn't expect you to be able to recover from - such as running out of memory.
javadoc for error says
An Error is a subclass of Throwable that indicates serious problems
that a reasonable application should not try to catch. Most such
errors are abnormal conditions.
whereas for Exception, the javadoc says
The class Exception and its subclasses are a form of Throwable that
indicates conditions that a reasonable application might want to
catch.
Some Differences
Error is not meant to be caught, even if you catch it you can not recover from it. For example during OutOfMemoryError, if you catch it you will get it again because GC may not be able to free memory in first place. On the other hand Exception can be caught and handled properly.
Error are often fatal in nature and recovery from Error is not possible which is different in case of Exception which may not be fatal in all cases.
Difference between Error and Exception in Java
Unlike Error, Exception is generally divided into two categories e.g. checked and unchecked Exceptions. Checked Exception has special place in Java programming language and require a mandatory try catch finally code block to handle it. On the other hand Unchecked Exception, which are subclass of RuntimeException mostly represent programming errors. Most common example of unchecked exception is NullPointerException in Java.
Similar to unchecked Exception, Error in Java are also unchecked. Compiler will not throw compile time error if it doesn't see Error handled with try catch or finally block. In fact handling Error is not a good Idea because recovery from Error is mostly not possible.
That's all on difference between Error and Exception in Java. key point to remember is that Error are fatal in nature and recovery may not be possible, on the other hand by carefully handling Exception you can make your code more robust and guard against different scenarios.
Look at a few of the subclasses of Error, taking from their respective javadoc:
AnnotationFormatError - Thrown when the annotation parser attempts to
read an annotation from a class file and determines that the
annotation is malformed.
AssertionError - Thrown to indicate that an assertion has failed.
LinkageError - Subclasses of LinkageError indicate that a class has
some dependency on another class; however, the latter class has
incompatibly changed after the compilation of the former class.
VirtualMachineError - Thrown to indicate that the Java Virtual Machine
is broken or has run out of resources necessary for it to continue
operating.
From the Error documentation:
An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch.
and the Exception documentation:
The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch.
I think this makes the distinction clear. Note also that both inherit from throwable and so can both be thrown.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java: checked vs unchecked exception explanation
Why are exceptions named checked and unchecked?
Why is the two exception types in Java named "checked" and "unchecked"? What is the reason behind choosing this type of exceptions ?
Checked exceptions extend java.lang.Exception, while unchecked exceptions extend java.lang.RuntimeException, or java.lang.Error.
Exception extends java.lang.Throwable, while RuntimeException extends Exception, and Error, like Exception, extends java.lang.Throwable.
When deciding whether you should be using a checked vs. unchecked exception, always remember these rules:
ExceptionS are cases an application would want to handle.
RuntimeExceptionS are cases you (usually) can't handle, due to programming error. You shouldn't catch RuntimeExceptionS, they should be targeted in your unit testing, and fixed in your production code.
ErrorS are cases you can't handle because of critical errors, such as system problems (e.g. file system has failed). You shouldn't ever throw, catch or subclass an Error, unless you're building something such as a compiler for the JVM.
The class RuntimeException and its subclasses, and the class Error and its subclasses are unchecked exceptions classes.The compiler doesn’t forces them to be declared in the throws clause. All the other exception classes that are part of Throwable hierarchy are checked exceptions.
unchecked exception classes are exempted from compile-time checking in java because they can occur at many points in the program and recovery from them is difficult or impossible. They also depend on the logic of the programmer. For example the OutOfMemory Exception is thrown when JVM cannot allocate any more memory to the program
I would like to throw a custom exception that will be determined at runtime. Currently I have to either add throws to the function or surround it with a try catch. What I want is for this exception to not be caught at all. It is a fatal exception and will show the programmer the error and what he can do to fix it. This is for an abstract class checking if initialization has been run first. I would like it to act like a NullPointerException, as when it occurs the program crashes.
Thanks
Subclass RuntimeException instead of Exception.
I obviously don't know the design decisions behind this, but it seems like there may be a better way to achieve whatever you're trying to do.
Make your custom exception a subclass of RuntimeException. These may be caught in a try/catch but this is not enforced by the compiler.
Your program should never just crash.
It should ideally log the backtrace and any related info that would help to debug the issue, and then exit notifying that something went wrong and where the details are logged.
You need unchecked exceptions, or exceptions that extend the RuntimeException class. By default, all unchecked exceptions are eventually caught by the default uncaught exception handler that prints the stack trace of the exception. Unless you have modified the default uncaught exception handler to be a different one, the behavior you observe on throwing unchecked exceptions will the same as the one you encounter when a NullPointerException (another unchecked exception) is thrown.
Note, that you will not see an exception stack trace if the unchecked exception is caught by a caller that acts on it without printing the stack trace. There is no difference in the manner in which unchecked and checked (those extending Exception instead of RuntimeException) exceptions are caught; there is only a difference in which the compiler treats checked and unchecked exceptions.
You should create a base exception (perhaps named Boobake4DomainException) extending RuntimeException, and then extend that for all your runtime exceptions.
Then you can just } catch (Boobake4DomainException e) { to be certain upstream if it is one of your own or not. This can make your problem handling code much simpler.
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?
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.
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.
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
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.
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).
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.
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...
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.
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
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.
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
User-defined Exception can be Checked Exception or Unchecked Exception, It depends on the class it is extending to.
User-defined Exception can be Custom Checked Exception, if it is extending to Exception class
User-defined Exception can be Custom Unchecked Exception , if it is extending to Run time Exception class.
Define a class and make it a child to Exception or Run time Exception