Organize Code
Execption
JavaScript
function divide(a, b) {
try {
if (b == 0)
throw new Error("divided by zero");
console.log(a/b);
} catch(e) {
console.log("Cannot divide by zero");
}
}
Try/Catch blocks are used for handling exceptions and errors that can happen in runtime.
Put the risky part of the code inside the try
block and specify what to do if an error happens inside catch
block.
function divide(a, b) {
try {
if (b == 0)
throw new Error("divided by zero");
console.log(a/b);
} catch(e) {
if (e instanceof EvalError) {
console.log(e.name + ': ' + e.message);
} else if (e instanceof Error) {
console.log("Cannot divide by zero");
} else {
console.log("Unknown Error");
}
}
}
JavaScript is not a type-safe language, so in order to catch a specific exception we need to use if
statements.
function divide(a, b) {
try {
if (b == 0)
throw new Error("divided by zero");
console.log(a/b);
} catch(e) {
console.log(e.name); // Error
console.log(e.message); // divided by zero
}
}
In JavaScript, Exceptions can be of any type.
Natively JavaScript itself throws Errors of type Error
.
Error
object has these properties on its prototype:
name
- Error namemessage
- Error message
function divide(a, b) {
try {
if (b == 0)
throw new Error("divided by zero");
console.log(a/b);
} catch(e) {
console.log("Cannot divide by zero");
} finally {
console.log("divide function executed");
}
}
The code inside the finally
block will always be executed after the Try/Catch block.
Even if you have a return
statement inside a try or catch blocks, the finally
block will be run before exiting the function.
function divide(a, b) {
try {
throw new Error("Error for no reason");
} catch(e) {
console.log("Executed all the time");
}
}
Error objects are a great way of organizing your code runtime errors.
If you're writing a Library or any reusable code, you want to throw
different Errors when different things go wrong, so that the users of your library can do different actions in each case.
Thrown Errors bubble up in the call stack until they are caught. If it is not caught, It will be caught by the JavaScript engine.