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
- Serious problems you should not try to catch or handle them
- It is not possible to recover from an error.
- Errors occur at runtime. That is why they are unknown to a compiler. Hence they are classified as “unchecked exceptions.”
- Unknown to a programmer
Exceptions
- Known to a programmer and can be guessed
- Caused by the application itself
- Exceptions can be “checked” or “unchecked.”
- 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!*/
Please comment if you want to discuss it further or if I missed something.
Thanks for reading.
Top comments (0)