Differences between Exception and Error
Asked Answered
L

11

203

I'm trying to learn more about basic Java and the different types of Throwables, can someone let me know the differences between Exceptions and Errors?

Lupus answered 26/5, 2009 at 19:39 Comment(0)
T
198

Errors should not be caught or handled (except in the rarest of cases). Exceptions are the bread and butter of exception handling. The Javadoc explains it well:

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.

Look at a few of the subclasses of Error, taking some of their JavaDoc comments:

  • 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.

There are really three important subcategories of Throwable:

  • Error - Something severe enough has gone wrong the most applications should crash rather than try to handle the problem,
  • Unchecked Exception (aka RuntimeException) - Very often a programming error such as a NullPointerException or an illegal argument. Applications can sometimes handle or recover from this Throwable category -- or at least catch it at the Thread's run() method, log the complaint, and continue running.
  • Checked Exception (aka Everything else) - Applications are expected to be able to catch and meaningfully do something with the rest, such as FileNotFoundException and TimeoutException...
Tadich answered 26/5, 2009 at 19:43 Comment(2)
Oracle says that Unchecked exceptions != RuntimeExceptions ; Unchecked exceptions = RuntimeExceptions + Errors. I know that it raises the question: Is error an exception?, but this is what they write. Here is just one of those examples: docs.oracle.com/javase/tutorial/essential/exceptions/… .Surprise
The unanswered question is how is RuntimeException and Error different in essence? Both are unchecked and equal in every other way.Amperage
M
51

This slide showing Java's exception hierarchy by @georgios-gousios concisely explains the differences between Errors and Exceptions in Java.

Java Exception Hierarchy

Mission answered 24/10, 2016 at 18:28 Comment(3)
I would love to see someone recovering from a NullPointerException :D:D:DChaplin
@IgnacioSolerGarcia It can be and it even has sense (the other question is if it is good). Normally you check if the object exists and after that call the method or use the field. But you can instead of checking for existence try catching NPE instead. And log a message about it and go on, for example.Rowe
@Gangnus: makes no sense. Remember that an exception skips parts of code and is a way to report errors, not normal operationsChaplin
U
20

Errors tend to signal the end of your application as you know it. It typically cannot be recovered from and should cause your VM to exit. Catching them should not be done except to possibly log or display and appropriate message before exiting.

Example: OutOfMemoryError - Not much you can do as your program can no longer run.

Exceptions are often recoverable and even when not, they generally just mean an attempted operation failed, but your program can still carry on.

Example: IllegalArgumentException - Passed invalid data to a method so that method call failed, but it does not affect future operations.

These are simplistic examples, and there is another wealth of information on just Exceptions alone.

Unabridged answered 26/5, 2009 at 19:47 Comment(1)
Look examples.javacodegeeks.com/java-basics/exceptions/… as example. IllegalArgumentException is Runtime exception, not Error. docs.oracle.com/javase/7/docs/api/java/lang/…Rowe
I
15

Errors -

  1. Errors in java are of type java.lang.Error.
  2. All errors in java are unchecked type.
  3. Errors happen at run time. They will not be known to compiler.
  4. It is impossible to recover from errors.
  5. Errors are mostly caused by the environment in which application is running.
  6. Examples : java.lang.StackOverflowError, java.lang.OutOfMemoryError

Exceptions -

  1. Exceptions in java are of type java.lang.Exception.
  2. Exceptions include both checked as well as unchecked type.
  3. Checked exceptions are known to compiler where as unchecked exceptions are not known to compiler because they occur at run time.
  4. You can recover from exceptions by handling them through try-catch blocks.
  5. Exceptions are mainly caused by the application itself.
  6. Examples : Checked Exceptions : SQLException, IOException
    Unchecked Exceptions : ArrayIndexOutOfBoundException, ClassCastException, NullPointerException

further reading : http://javaconceptoftheday.com/difference-between-error-vs-exception-in-java/ https://static.mcmap.net/file/mcmap/ZG-Ab5ovKRphcm_jaR2jX7BAaRXAZFykW7kQWRft/wp-content/uploads/2015/04/ErrorVsException.png

Infanticide answered 15/9, 2017 at 6:19 Comment(0)
M
9

Sun puts it best:

An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch.

Molina answered 26/5, 2009 at 19:48 Comment(0)
G
5

The description of the Error class is quite clear:

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. The ThreadDeath error, though a "normal" condition, is also a subclass of Error because most applications should not try to catch it.

A method is not required to declare in its throws clause any subclasses of Error that might be thrown during the execution of the method but not caught, since these errors are abnormal conditions that should never occur.

Cited from Java's own documentation of the class Error.

In short, you should not catch Errors, except you have a good reason to do so. (For example to prevent your implementation of web server to crash if a servlet runs out of memory or something like that.)

An Exception, on the other hand, is just a normal exception as in any other modern language. You will find a detailed description in the Java API documentation or any online or offline resource.

Gamone answered 26/5, 2009 at 19:50 Comment(0)
W
3

There is several similarities and differences between classes java.lang.Exception and java.lang.Error.

Similarities:

  • First - both classes extends java.lang.Throwable and as a result inherits many of the methods which are common to be used when dealing with errors such as: getMessage, getStackTrace, printStackTrace and so on.

  • Second, as being subclasses of java.lang.Throwable they both inherit following properties:

    • Throwable itself and any of its subclasses (including java.lang.Error) can be declared in method exceptions list using throws keyword. Such declaration required only for java.lang.Exception and subclasses, for java.lang.Throwable, java.lang.Error and java.lang.RuntimeException and their subclasses it is optional.

    • Only java.lang.Throwable and subclasses allowed to be used in the catch clause.

    • Only java.lang.Throwable and subclasses can be used with keyword - throw.

The conclusion from this property is following both java.lang.Error and java.lang.Exception can be declared in the method header, can be in catch clause, can be used with keyword throw.

Differences:

  • First - conceptual difference: java.lang.Error designed to be thrown by the JVM and indicate serious problems and intended to stop program execution instead of being caught(but it is possible as for any other java.lang.Throwable successor).

    A passage from javadoc description about java.lang.Error:

    ...indicates serious problems that a reasonable application should not try to catch.

    In opposite java.lang.Exception designed to represent errors that expected and can be handled by a programmer without terminating program execution.

    A passage from javadoc description about java.lang.Exception:

    ...indicates conditions that a reasonable application might want to catch.

  • The second difference between java.lang.Error and java.lang.Exception that first considered to be a unchecked exception for compile-time exception checking. As the result code throwing java.lang.Error or its subclasses don't require to declare this error in the method header. While throwing java.lang.Exception required declaration in the method header.

Throwable and its successor class diagram (properties and methods are omitted). enter image description here

Wassail answered 4/5, 2016 at 14:59 Comment(0)
S
1

IMO an error is something that can cause your application to fail and should not be handled. An exception is something that can cause unpredictable results, but can be recovered from.

Example:

If a program has run out of memory it is an error as the application cannot continue. However, if a program accepts an incorrect input type it is an exception as the program can handle it and redirect to receive the correct input type.

Stringpiece answered 26/5, 2009 at 19:50 Comment(0)
G
1

Errors are mainly caused by the environment in which application is running. For example, OutOfMemoryError occurs when JVM runs out of memory or StackOverflowError occurs when stack overflows.

Exceptions are mainly caused by the application itself. For example, NullPointerException occurs when an application tries to access null object or ClassCastException occurs when an application tries to cast incompatible class types.

Source : Difference Between Error Vs Exception In Java

Gingergingerbread answered 27/4, 2015 at 14:10 Comment(1)
"Errors are mainly caused by the environment in which application is running" and "Exceptions are mainly caused by the application itself" perfect!Heronry
S
0

Here's a pretty good summary from Java API what an Error and Exception represents:

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. The ThreadDeath error, though a "normal" condition, is also a subclass of Error because most applications should not try to catch it.

A method is not required to declare in its throws clause any subclasses of Error that might be thrown during the execution of the method but not caught, since these errors are abnormal conditions that should never occur.

OTOH, for Exceptions, Java API says:

The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch.

Simmons answered 26/5, 2009 at 19:50 Comment(0)
B
0

Errors are caused by the environment where your application or program runs. Most times, you may not recover from it as this ends your application or program. Javadoc advised that you shouldn't bother catching such errors since the environment e.g. JVM, on such errors is going to quit anyway.

Examples: VirtualMachineError - Thrown to indicate that the Java Virtual Machine is broken or has run out of resources necessary for it to continue operating. OutOfMemoryError occurs when JVM runs out of memory or StackOverflowError occurs when stack runs over.

Exceptions are caused by your application or program itself; maybe due to your own mistake. Most times you can recover from it and your application would still continue to run. You are advised to catch such errors to prevent abnormal termination of your application or program and/or to be able to customize the exception message so the users see a nicely formatted message instead of the default ugly exception messages scattered all over the place.

Examples: NullPointerException occurs when an application tries to access null object. or Trying to access an array with a non-existing index or calling a function with wrong data or parameters.

Bourke answered 19/5, 2020 at 10:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.