The try-catch-finally block in JavaScript offers an error-handling method to capture runtime issues. JavaScript is a loosely-typed language. It does not produce errors at compile time.
try
{
// code
}
catch(error)
{
// If an error occurs, this code block will be executed.
}
finally{
// Whether or not an error occurs, this code block will be executed.
}
Lets try to generate an error without try catch block
var value = add (5, 10);
console.log(value)
var value = add (5, 10);
^
ReferenceError: add is not defined
Now lets handle same error using try catch block
try
{
var value = add (10, 20);
}
catch(error)
{
console.log("Catch executed")
}
Catch executed
Whether or not an error occurs, finally code block will be executed. Lets take an example of finally block.
try
{
var value = add (10, 20);
}
catch(error)
{
console.log("Catch executed")
}
finally{
console.log("finally executed")
}
Catch executed
finally executed
throw is used to create your own exception.
try {
throw "Custom error occurred";
}
catch(error) {
}
Example 2
try
{
throw {
code: 101,
message: "Error occurred"
};
}
catch (error) {
console.log(error.code + "- " + error.message);
}
Lets throw an exception using throw
const number = -10;
try {
if(number > 0) {
console.log('true');
}
else {
// custom throw statement
throw new Error('false');
}
// Below code executes only if the statement is true
console.log('Positive number');
}
catch(error) {
console.log('Message: ' + error);
}
Message: Error: false
Now lets take an positive number
const number = 10;
try {
if(number > 0) {
console.log('true');
}
else {
// custom throw statement
throw new Error('false');
}
// Below code executes only if the statement is true
console.log('Positive number');
}
catch(error) {
console.log('Message: ' + error);
}
true
Positive number