The try statement defines a block of code to attempt execution.
The catch statement defines a block of code to handle any errors that occur.
The finally statement defines a block of code that runs regardless of whether an error occurs.
The throw statement is used to create a custom error.
When running JavaScript code, various types of errors can occur. These may include coding mistakes made by the programmer, errors caused by incorrect input, or other unexpected issues.
In this example, we intentionally misspelled “alert” as “adddlert” to trigger an error.
<p id=”demo”></p> <script> try { adddlert(“Welcome guest!”); } catch(err) { document.getElementById(“demo”).innerHTML = err.message; } </script> |
JavaScript detects “adddlert” as an error and executes the catch block to handle it. |