DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 963,673 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for Difference Between Error and Exception With Examples
Fahim Zada
Fahim Zada

Posted on

Difference Between Error and Exception With Examples

Errors occur when something wrong or invalid happens in the code or the program's environment in which it is running. It can be syntax, logical or runtime errors, and from the environment, it can be a lack of resources or version incompatibilities etc.
Exceptions are thrown by a programmer when certain conditions in the code are being met by using the throw keyword. And we can catch the exception by using the try and catch block.

Errors

  1. Serious problems you should not try to catch or handle them
  2. It is not possible to recover from an error.
  3. Errors occur at runtime. That is why they are unknown to a compiler. Hence they are classified as β€œunchecked exceptions.”
  4. Unknown to a programmer

Exceptions

  1. Known to a programmer and can be guessed
  2. Caused by the application itself
  3. Exceptions can be β€œchecked” or β€œunchecked.”
  4. The try and catch blocks can handle exceptions and recover the application from them.
//You can copy and paste the code into your console tab
//You can throw a string, object or even error

//Throwing string message
try {
    throw "throwing string"
} catch (ex) {
    console.log(ex);
}

//VM54:4 throwing string

//Throwing an error
try {
    throw new Error("throwing string")
} catch (ex) {
    console.log(ex);
}

/*VM158:4 Error: throwing string
    at <anonymous>:2:11
*/

//As of Echma 2022 we can use the cause with error
try {
    throw new Error("throwing string", {cause: "Just like that"})
} catch (ex) {
    console.log(ex, ex.cause);
}

/*VM342:4 Error: throwing string
    at <anonymous>:2:11 'Just like that'
*/

//throwing object
try {
    throw {msg: "Condition met"}
} catch (ex) {
    console.log(ex);
}

//VM517:4 {msg: 'Condition met'}

//Of course we can use finally too

try {
    throw "With finally"
} catch (ex) {
    console.log(ex);
} finally {
    console.log("I'm going to run no matter what!")
}

/*VM5528:4 With finally
VM5528:6 I'm going to run no matter what!*/
Enter fullscreen mode Exit fullscreen mode

Please comment if you want to discuss it further or if I missed something.

Thanks for reading.

Top comments (0)

DEV has this feature:

Settings

Go to your customization settings to nudge your home feed to show content more relevant to your developer experience level. πŸ›