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!
Based on the lecture, the Errors are thrown by JavaScript engine and exception are thrown by developer. it is only naming convention.
- JavaScript throws Errors
- Developers throws Exceptions
In technical aspect is the same structure (thing).