The try statement lets you test a block of code for errors.
The catch statement lets you handle the error.
The throw statement lets you create custom errors.
When the JavaScript engine is executing JavaScript code, different errors can occur:
It can be syntax errors, typically coding errors or typos made by the programmer.
It can be misspelled or missing features in the language (maybe due to browser differences).
It can be errors due to wrong input, from a user, or from an Internet server.
And, of course, it can be many other unforeseeable things.
When an error occurs, when something goes wrong, the JavaScript engine will normally stop, and generate an error message.
The technical term for this is: JavaScript will throw an error.
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 JavaScript statements try and catch come in pairs.
In the example below we have deliberately made a typo in the code in the try block.
The catch block catches the error in the try block, and executes code to handle it:
The throw statement allows you to create a custom error.
The correct technical term is to create or throw an exception.
If you use the throw statement together with try and catch, you can control program flow and generate custom error messages.
The exception can be a JavaScript String, a Number, a Boolean or an Object.
This example examines the value of an input variable. If the value is wrong, an exception (error) is thrown. The error is caught by the catch statement and a custom error message is displayed:
Note that the example above will also throw an error if the getElementById function fails.
The perfect solution for professionals who need to balance work, family, and career building.
More than 10 000 certificates already issued!
The HTML Certificate documents your knowledge of HTML.
The HTML5 Certificate documents your knowledge of advanced HTML5.
The CSS Certificate documents your knowledge of advanced CSS.
The JavaScript Certificate documents your knowledge of JavaScript and HTML DOM.
The jQuery Certificate documents your knowledge of jQuery.
The XML Certificate documents your knowledge of XML, XML DOM and XSLT.
The ASP Certificate documents your knowledge of ASP, SQL, and ADO.
The PHP Certificate documents your knowledge of PHP and SQL (MySQL).
Your message has been sent to W3Schools.