JavaScript From Beginner To Advanced

0% completed

Previous
Next
JavaScript - try...catch

In JavaScript, when an error occurs during the execution of a script, it can halt the entire program if not handled properly. This abrupt stopping not only affects user experience but can also prevent essential code from running, which might lead to incomplete transactions, corrupted data, or a broken user interface.

What Happens Without Error Handling?

To understand the impact of unhandled errors, consider the following example:

Javascript
Javascript

. . . .
  • In this script, someUndefinedFunction() is called but not defined anywhere, leading to a ReferenceError.
  • Without error handling, the script stops executing as soon as the error occurs, and "End of script" is never printed. The error is thrown to the console, and the script execution is terminated.

This example highlights the need for proper error management to ensure the continuity of script execution even when an error is encountered.

Implementing Try...Catch

Image

The try...catch structure in JavaScript allows you to handle errors gracefully. It enables the script to catch thrown errors in a controlled manner, allowing the rest of the code to continue executing.

Syntax

Javascript
Javascript
. . . .
  • Try Block: This block contains code that is potentially error-prone. JavaScript attempts to execute this code, and if anything goes wrong, it throws an error and immediately transfers control to the catch block.
  • Catch Block: This block catches the thrown error. The parameter (traditionally named error) contains information about what went wrong.

Example

Javascript
Javascript

. . . .
  • Explanation:
    • The script starts by logging "Start of script."
    • The try block contains a call to someUndefinedFunction(). Since this function does not exist, JavaScript throws a ReferenceError.
    • Normally, any code after the error within the same try block would be skipped. In this example, the console.log("This will not be executed...") line is not executed.
    • Execution moves to the catch block where the error is caught. The error message is logged to the console.
    • Importantly, the script does not terminate prematurely. "End of script" is logged, demonstrating that the program continues after handling the error.

This approach to error handling not only prevents the application from crashing but also provides a mechanism to handle errors in a way that can be logged, reported, or even used to trigger other corrective actions without stopping the entire program. Next, we'll explore how to use the finally block to execute code regardless of the result of the try...catch execution.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next