JavaScript Page 4 - JavaScript Exception Handling |
Now, what you just saw was a very primitive exception handler, albeit one which isn't very useful on a production site. Ideally, you'd want the message generated by the exception handler to be a little more descriptive, and to contain some information on the source of the error. JavaScript satisfies this requirement via two special, pre-defined properties of the Error object generated by an exception - the "name" and "message" properties. Take a look: <script language="JavaScript"> Here's the output: An exception occurred in the script. Error name: TypeError. Error message: 'colours' is undefinedDon't want to use the alert() box because it's disruptive and annoying? Write the output directly to the page itself with the writeln() method instead, as below: It's also possible to write an exception handler to ignore all errors generated in your script - the following example demonstrates: <script language="JavaScript"> In this case, it doesn't matter what type of exception JavaScript generates It should be noted, however, that this approach, although extremely simple, is *not* recommended for general use. It is poor programming practice to trap all errors, regardless of type, and ignore them; it is far better - and more professional - to anticipate the likely errors ahead of time, and use the "try-catch" construct to isolate and resolve them.
blog comments powered by Disqus |