JavaScript is a loosely typed language. Sometimes runtime errors occur when accessing undefined variables or calling undefined functions.
JavaScript provides an error-handling mechanism using:
These statements help prevent programs from crashing when errors occur.
The try block contains code that may generate an error.
If an error occurs, JavaScript immediately transfers control to the catch block.
The catch block executes when an error occurs inside the try block.
Since the function Sum() is not defined, an error occurs and is handled by the catch block.
The parameter inside catch contains details about the error.
You can display or log the error message using the error object.
The finally block always executes whether an error occurs or not.
Finally block executed
The finally block runs regardless of whether an error occurs.
The finally block is useful for cleanup operations.
The throw keyword is used to generate custom errors.
Error occurred
You can use throw to validate user input.
You must be 18 or older
| Error Type | Description |
|---|---|
| ReferenceError | Undefined variable or function |
| TypeError | Invalid operation on a value |
| RangeError | Number out of allowed range |
| URIError | Invalid URI function usage |
| SyntaxError | Invalid JavaScript syntax |
| Keyword | Purpose |
|---|---|
| try | Contains code that may generate errors |
| catch | Handles errors |
| finally | Always executes |
| throw | Creates custom errors |
Which block always executes whether an error occurs or not?