HTML and CSS Reference
In-Depth Information
With errors like this, users will likely stop coming to the website or using the application.
To prevent such issues, you need to wrap the code in a try block:
try{
window.dosomeunsupportedmethod();
} catch (e) {
alert("Browser does not support the desired functionality.");
}
By using the
try…catch
block, you can handle the error condition gracefully. The users see
a standard alert and the webpage continues to run as usual. This example code results in the
message shown in Figure 2-4.
FIGURE 2-4
A clean message box to show errors
The
try…catch
block is divided into two parts. The first part, the
try
portion, says, “Try to
do this work.” If anything goes wrong when trying to do the work, the
catch
block receives
an
exception
object with information about the error. Any code inside the try portion of the
try…catch
block is protected against encountering an unhandled error.
The
catch
block is where the error can be handled as appropriate for the application. The
catch
block receives a parameter that is an
exception
object. Table 2-8 shows the properties
for the
exception
object.
TABLE 2-8
Properties available on the
exception
object
Property
Description
A textual description of the error that occurred
message
A numeric error code
number
The name of the
exception
object
name
You can use the information provided in the
exception
object to decide what to do in
terms of overall program flow. For example, if the program needs access to a resource that
it can't have and an exception is thrown, the program can fall back to a different process
to achieve the desired functionality or simply tell the user that something needs to be
changed—for example, if cookies or another HTML5 API are required for the site to work.
Other ways to check for this type of thing are demonstrated shortly.
Search WWH ::
Custom Search