Differences Between Exception and Error

What is difference between Errors and Exceptions?

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

while

An Exception "indicates conditions
that a reasonable application might
want to catch."

Error along with RuntimeException & their subclasses are unchecked exceptions. All other Exception classes are checked exceptions.

Checked exceptions are generally those from which a program can recover & it might be a good idea to recover from such exceptions programmatically. Examples include FileNotFoundException, ParseException, etc. A programmer is expected to check for these exceptions by using the try-catch block or throw it back to the caller

On the other hand we have unchecked exceptions. These are those exceptions that might not happen if everything is in order, but they do occur. Examples include ArrayIndexOutOfBoundException, ClassCastException, etc. Many applications will use try-catch or throws clause for RuntimeExceptions & their subclasses but from the language perspective it is not required to do so. Do note that recovery from a RuntimeException is generally possible but the guys who designed the class/exception deemed it unnecessary for the end programmer to check for such exceptions.

Errors are also unchecked exception & the programmer is not required to do anything with these. In fact it is a bad idea to use a try-catch clause for Errors. Most often, recovery from an Error is not possible & the program should be allowed to terminate. Examples include OutOfMemoryError, StackOverflowError, etc.

Do note that although Errors are unchecked exceptions, we shouldn't try to deal with them, but it is ok to deal with RuntimeExceptions(also unchecked exceptions) in code. Checked exceptions should be handled by the code.

Differences between Exception and Error

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

what is the diffrence between error and exception

That is generally correct. Although the terms are colloquially interchangeable in many domains.

An Error, also known as a compile-time error, is a statement of fact. (Or NOT fact) The compiler is unable to compile the output.

  • Technically an error is a state in code that has raised an exception in the compiler's runtime :)

An Exception is raised at runtime and is the result of an exceptional combination of values.

Because an Exception is raised at runtime, we can generally write code to catch and handle or workaround an exception within your script or code. An Error prevents the code from being compiled and thus executed at all, so our only option is to modify the code to resolve an Error.

A compiler may perform syntax and sometimes type checking to ensure that the code follows a set of pre-determined rules and can be compiled into executable statements, but it is not until invalid values are passed into those statements that an Exception can occur, that is harder for a compiler to do and so is generally only detected at Runtime.

Some advanced or specialised compilers may perform checks against common values and as a programer you can write unit tests to try and pre-emptively detect exceptions before releasing your code.

What's the difference between Error and Exception in Javascript?

JavaScript syntax

Errors and exceptions are syntactically synonymous in JavaScript. The language only implements the Error keyword (through window.Error). You may define custom errors, using the Error.constructor, which takes name and message as parameters.

JavaScript Error

There is also the line number sugar that can be used to trace bug occurrences inside the code. JavaScript only has Error. Whether you hear people talking about Exceptions or Errors, in JavaScript they refer to the same thing.

Browsers make a distinction: ReferenceError (when accessing a variable with a name that doesn't exist in the heap, or when you make a typo(more here.), TypeError is also a known JS error, more here.

JavaScript Exception

A known JavaScript Exception is DOM Exception 8. It occurs when you access an object that is not ready, such as an XMLHttpRequest that has not completed the request.

Implementation

When using try catch or try catch finally blocks, you will deal with both JavaScript Exception and Error. Code-wise the difference has no impact.

Behind the scenes, the browsers use the same window.Error constructor. An Exception is an Error instance with a name and message that contain "Exception".

Try: var myCustomError = new Error("myException", "An exception occurred.");. "Exception" is text in a string. More on Error here.

Convention

By convention, there is a difference between Error and Exception. An Error indicates a clear violation. A TypeError or ReferenceError means you are not following the language specs.

An Exception is thrown when you access an XMLHttpRequest response before it is complete. Error is a "you broke the law" shout and Exception is an "Almost there!" pad on the shoulder. Hope the analogy helps!

What is the difference between Runtime Exception in java and Runtime Error in java?

I Googled for that sentence, and it appears in a sample answer to what appears to be a sample exam question.

(d) Name the type of error (syntax, runtime or logical error) in each case given below:

(i) Math.sqrt (36-45)

(ii) int a;b;c;

This question shows up in a lot of different search results. The funny thing is that while they all agree that (ii) is a syntax error, they disagree on the answer to (i). Some say it is a runtime error, others a logic error1.

The real answer is the correct answer to (i) depends on the context.

  • In some programming languages, this may result in a runtime exception.
  • In other programming languages, it will produce the value NaN.
  • In a programming language that natively supported complex numbers, the answer would be 3i.

To determine whether this is an error at all, you first need to know which programming language we are talking about. It looks like Java2, but there are other possibilities. Then you need to decide whether the program is expecting the predicted exception or NaN or whatever. Consider this Java example:

try {
int a = 1;
int b = 0;
int c = a / b; // This will throw an exception in Java.
} catch (AritheticException ex) {
System.out.println("Success!");
}

The division by zero in the above is (arguably) not an error at all. We were expecting it, and we handled it. An exception in Java is a way to signal an exceptional event. It is not necessarily a runtime error.

Back to the original sqrt(-9) example, in that case Java does not throw an exception. Instead it returns NaN which is a legitimate IEE 768 floating point value. Is that an error? Well it actually depends on that the program does with that value.

In short: the question is ambiguous, and doesn't have a single correct answer.

It is a shame that school curricula are perpetuating this kind of thinking. One would hope that both "runtime error" and "logical error" would be accepted as correct answers if this particular question came up in a real exam. But ...


1 - One answer even said it was a syntax error because there is no semicolon.

2 - Even assuming this is Java, Math.sqrt is not necessarily the java.lang.Math.sqrt(double) method. It could be a different Math class, or if the programmer is ignoring style, Math could even be a variable name.

Exceptions vs Errors in Python

  1. Yes. SyntaxError isn't catchable except in cases of dynamically executed code (via eval/exec), because it occurs before the code is actually running.
  2. "Fatal" means "program dies regardless of what the code says"; that doesn't happen with exceptions in Python, they're all catchable. os._exit can forcibly kill the process, but it does so by bypassing the exception mechanism.
  3. There is no difference between exceptions and errors, so the nomenclature doesn't matter.
  4. System-exiting exceptions derive from BaseException, but not Exception. But they can be caught just like any other exception
  5. Warnings behave differently based on the warnings filter, and deriving from Exception means they're not in the "system-exiting" category
  6. AssertionError is just another Exception child class, so it's not "system exiting". It's just tied to the assert statement, which has special semantics.
  7. Things deriving from BaseException but not Exception (e.g. SystemExit, KeyboardInterrupt) are "not reasonable to catch" (or if you do catch them, it should almost always be to log/perform cleanup and rethrow them), everything else (derived from Exception as well) is "conditionally reasonable to catch". There is no other distinction.

To be clear, "system-exiting" is just a way of saying "things which except Exception: won't catch"; if no except blocks are involved, all exceptions (aside from warnings, which as noted, behave differently based on the warnings filter) are "system-exiting".

Python: difference between ValueError and Exception?

ValueError inherits from Exception. You can decide to trap either only ValueError, or Exception, that's what exception inheritance is for.

In this example:

try:
a=12+"xxx"
except Exception:
# exception is trapped (TypeError)

exception is trapped, all exceptions (except BaseException exceptions) are trapped by the except statement.

In this other example:

try:
a=12+"xxx"
except ValueError:
# not trapped

Here, exception is NOT trapped (TypeError is not ValueError and does not inherit)

You generally use specific exceptions to trap only the ones that are likely to occur (best example is IOError when handling files), and leave the rest untrapped. The danger of catching all exceptions is to get a piece of code that does not crash, but does nothing.

(editing the answer in response to your edit:) when you raise an exception: you're creating an instance of Exception which will be filtered out by future except ValueError: statements. the message is different because the representation of the exception (when printed) includes the exception class name.

What is the difference between Exception and Throwable classes?

Actually, Scala reuses exception structure from Java (so Throwable comes from Java). The class hierarchy looks like this:

         Throwable
|
------------------
| |
Error Exception
| |
errors |
-------------------
| |
runtime exceptions checked exceptions

Throwable is the superclass of all errors in Java.

Error is the superclass for errors, that are not recoverable like VirtualMachineError or ThreadDeath. Errors can be intercepted using try-catch, but usually, it's not a good practice.

Child classes of Exception are exceptions, that are intended to handled programmatically by intercepting them using try-catch.

Java also makes the difference between runtime and checked exceptions, that checked exception need to be mandatorily handled by try-catch.

Scala though handles all exceptions as runtime, so intercepting them is voluntary.

Scala has also extractor named NonFatal, which can be used to pattern match non-fatal Throwables. For example:

try {
// dangerous stuff
} catch {
//will NOT match fatal errors like VirtualMachineError, ThreadDeath, LinkageError etc.
case NonFatal(e) => log.error(e, "Something not that bad.")
}


Related Topics



Leave a reply



Submit