JavaScript Page 7 - JavaScript Exception Handling |
Thus far, you've been working with JavaScript's built-in exceptions, which can handle most logical or syntactical errors. However, JavaScript also allows you to get creative with exceptions, by generating your own custom exceptions if the need arises. This is accomplished via JavaScript's "throw" statement, which is used to raise errors which can be detected and resolved by the "try" family of exception handlers. The "throw" statement needs to be passed an error type. When the exception is raised, this exception name and description will be made available to the defined exception handler. Let's go to a quick example. In the following piece of code, if the value entered into the form field is greater than 99, the code will manually generate a RangeError exception, which will be caught and displayed appropriately. <html> You can also create your own exceptions, via the JavaScript Error constructor. The following example demonstrates, by creating a custom error type called idiotUserError. In this case, when you run the script, a new Error object will be created named idiotUserError, with the message specified in the Error object constructor. This error can now be thrown using the regular "throw" statement, as in the example above. Let's try a more useful example: <html> In this case, if the value entered into the form is blank or not "john", a custom exception will be thrown by the code. This custom exception can be caught by a generic exception handler such as the one used above, and the exception can be routed and resolved appropriately
blog comments powered by Disqus |