3.8. Handling Exceptions

JavaScript supports a familiar type of exception handling for C# developers. Code can throw an exception. If located inside a try block, a corresponding catch block can handle the exception. After that, a finally block will execute to take care of any necessary cleanup or global recovery approach. The try-catch-finally pattern is important in being able to write robust code that can recover from error conditions.

The Java runtime environment (not JavaScript) requires that code declare up front any type of exception that it may want to catch. When the code is compiled, the types of exceptions that may be thrown are checked. You must explicitly catch all of the possible exception types. Unlike the Java runtime environment, the .NET Framework does not require you to declare what type of exception a method may throw. You can catch the base-exception type and then deal with more specific exception types as you see fit. You can even define custom exception types derived from existing types for greater specialization. In JavaScript, there are no static checks on types of exceptions. You simply catch the exception, which has a base type of object, and react as you see fit. It is not uncommon to have exception-handling code that looks at the details of the exception thrown to determine what the course of action should be. In many situations, throwing a basic Exception object using a string constructor is adequate for signaling what recovery action is necessary. ...

Get Professional ASP.NET 3.5 AJAX now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.