Errors Will Happen!
Errors can be coding errors made by the programmer, errors due to wrong input, and other unforeseeable things.
In this example we have written alert as adddlert to deliberately produce an error:
The catch block catches addlert as an error, and executes code to handle it.
The try statement allows you to define a block of code to be tested for errors while it is being executed.
The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
The throw Statement
The throw statement allows you to create a custom error.
Technically you can raise (throw) an exception.
If you use throw together with try and catch, you can control program flow and generate custom error messages.
Input Validation Example
This example examines input. If the value is wrong, an exception (err) is thrown.
The exception (err) is caught by the catch statement and a custom error message is displayed:
The code above is just an example.
You can read more about forms validation in a later chapter of this tutorial.
The finally Statement
The finally statement lets you execute code, after try and catch, regardless of the result: