The try...catch statement allows you to test a block of code for errors.
The try...catch Statement
The try...catch statement allows you to test a block of code for errors. The try block contains the code to be run, and the catch block contains the code to be executed if an error occurs.
The next example uses a confirm box to display a custom message telling users they can click OK to continue viewing the page or click Cancel to go to the homepage. If the confirm method returns false, the user clicked Cancel, and the code redirects the user. If the confirm method returns true, the code does nothing:
The throw Statement
The throw statement can be used together with the try...catch statement, to create an exception for the error. Learn about the throw statement in the next chapter.