In this tutorial, we are going to explore how to handle errors in JavaScript using Try-Catch statements. This technique is a part of error handling mechanisms in JavaScript which can help you catch runtime errors before they crash your application and help to debug your application more effectively.
You will learn how to:
Prerequisites:
In JavaScript, the try..catch
statement marks a block of statements to try, and specifies one or more responses should an exception be thrown. If an exception is thrown, the try..catch
statement catches it.
The syntax is as follows:
try {
// code here...
} catch(error) {
// handle error here...
}
try
: This keyword is used to specify the code that could potentially throw an error.catch
: This keyword is used to capture the error (if any) thrown inside the try block.try {
// Trying to declare a variable with a reserved keyword
let throw = 'test';
} catch(error) {
console.log(error);
// expected output: SyntaxError: Unexpected token 'throw'
}
In this example, we are trying to declare a variable with a reserved keyword, which results in a SyntaxError
. The catch
block captures this error and logs it to the console.
try {
// Trying to access an undefined variable
console.log(x);
} catch(error) {
console.log(error);
// expected output: ReferenceError: x is not defined
}
In this example, we are trying to access an undefined variable 'x', which results in a ReferenceError
. The catch
block captures this error and logs it to the console.
In this tutorial, you learned how to handle errors in JavaScript using Try-Catch statements. This is an important concept in JavaScript and can help to make your applications more robust and easier to debug.
Next steps for learning:
finally
statement in JavaScript.Additional resources:
Exercise 1: Write a function divide(a, b)
that takes two parameters and returns the result of a / b
. If b
is 0
, throw an error.
Solution:
function divide(a, b) {
try {
if(b == 0) {
throw new Error("Division by zero not allowed");
}
return a / b;
} catch(error) {
console.log(error);
}
}
divide(10, 0);
// expected output: Error: Division by zero not allowed
Exercise 2: Write a function getProp(obj, key)
that takes an object and a key as parameters and returns the value of the key in the object. If the key is not present in the object, throw an error.
Solution:
function getProp(obj, key) {
try {
if(!obj.hasOwnProperty(key)) {
throw new Error("Key not found in object");
}
return obj[key];
} catch(error) {
console.log(error);
}
}
let obj = {name: 'John', age: 30};
getProp(obj, 'city');
// expected output: Error: Key not found in object
In both exercises, we're checking for a specific condition and if the condition is met, we throw an error which is then caught by the catch
block.
Tips for further practice:
finally
statement and use it in your code.