JavaScript try, catch, and finally

In this chapter, we will learn about the try, catch, and finally statements in JavaScript. These statements are used for handling exceptions and ensuring that code runs smoothly even when errors occur. We will cover:

  • What are try, catch, and finally?
  • The try Block
  • The catch Block
  • The finally Block
  • Throwing Errors
  • Simple Programs using try, catch, and finally

What are try, catch, and finally?

The try, catch, and finally statements are used to handle exceptions in JavaScript. They provide a way to catch errors and execute code regardless of whether an error occurred.

  • try: Contains the code that may throw an error.
  • catch: Contains the code to handle the error if one occurs in the try block.
  • finally: Contains the code that will always be executed, regardless of whether an error occurred.

The try Block

The try block contains code that may potentially throw an error. If an error occurs, the execution of the try block is stopped, and control is passed to the catch block.

Syntax

try { // Code that may throw an error } 

Example

try { let result = 10 / 0; console.log(result); } catch (error) { console.log("An error occurred:", error.message); } 

Output:

Infinity 

The catch Block

The catch block contains code that will be executed if an error occurs in the try block. The catch block can access the error object, which contains information about the error.

Syntax

try { // Code that may throw an error } catch (error) { // Code to handle the error } 

Example

try { let result = 10 / 0; console.log(result); } catch (error) { console.log("An error occurred:", error.message); } 

Output:

Infinity 

The finally Block

The finally block contains code that will always be executed, regardless of whether an error occurred. It is useful for cleaning up resources or performing tasks that must always be completed.

Syntax

try { // Code that may throw an error } catch (error) { // Code to handle the error } finally { // Code that will always be executed } 

Example

try { let result = 10 / 0; console.log(result); } catch (error) { console.log("An error occurred:", error.message); } finally { console.log("This will always be executed."); } 

Output:

Infinity This will always be executed. 

Throwing Errors

You can throw custom errors using the throw statement. This allows you to create meaningful error messages and handle specific error conditions.

Syntax

throw new Error("Custom error message"); 

Example

function divide(a, b) { if (b === 0) { throw new Error("Division by zero is not allowed."); } return a / b; } try { let result = divide(10, 0); console.log(result); } catch (error) { console.log("An error occurred:", error.message); } finally { console.log("Division attempt completed."); } 

Output:

An error occurred: Division by zero is not allowed. Division attempt completed. 

Simple Programs using try, catch, and finally

Program 1: Validating User Input

function validateAge(age) { if (isNaN(age)) { throw new Error("Age must be a number."); } if (age < 0 || age > 120) { throw new Error("Age must be between 0 and 120."); } return "Valid age: " + age; } try { let userAge = validateAge(25); console.log(userAge); userAge = validateAge(-5); // This should trigger an error } catch (error) { console.log("An error occurred:", error.message); } finally { console.log("Validation attempt completed."); } 

Output:

Valid age: 25 An error occurred: Age must be between 0 and 120. Validation attempt completed. 

Program 2: Reading a JSON File

function parseJSON(jsonString) { try { let data = JSON.parse(jsonString); console.log("Parsed JSON:", data); } catch (error) { console.log("An error occurred:", error.message); } finally { console.log("JSON parsing attempt completed."); } } let jsonString = '{"name": "Ramesh", "age": 25}'; parseJSON(jsonString); jsonString = '{"name": "Ramesh", "age": 25'; // This should trigger an error parseJSON(jsonString); 

Output:

Parsed JSON: { name: 'Ramesh', age: 25 } An error occurred: Unexpected end of JSON input JSON parsing attempt completed. JSON parsing attempt completed. 

Conclusion

In this chapter, you learned about the try, catch, and finally statements in JavaScript, including their syntax and usage. We also provided various use cases with simple programs to demonstrate the usage of error handling. Proper error handling is essential for writing robust and reliable JavaScript code.

Leave a Comment

Scroll to Top