Java Reference
In-Depth Information
Throwing errors can be very useful for indicating problems such as invalid user input. Rather
than using lots of
if...else
statements, you can check the validity of user input, then use
throw
to stop code execution in its tracks and cause the error‐catching code in the
catch
block of code to take over. In the
catch
clause, you can determine whether the error is based
on user input, in which case you can notify the user what went wrong and how to correct it.
Alternatively, if it's an unexpected error, you can handle it more gracefully than with lots of
JavaScript errors.
You can throw anything; from a simple string or number to an object. In most cases, however, you'll
throw an object. To use
throw
, type
throw
and include the object after it. For example, if you are
validating a set of form fields, your exception object could contain not only the message, but the
id
of the element that has invalid data. An example could look like this:
throw {
message : "Please type a valid email address",
elementId : "txtEmail"
};
The objects you throw should include at least a
message
property; most error‐handling code will be
looking for it.
try…catch and throwing Errors
trY it out
In this example you modify
ch16 _ example2.html
to use the
try...catch
and
throw
statements to
validate the e‐mail and username fields. Feel free to use
ch16 _ example2.html
as a basis for this new
file. For your convenience, the following code listing highlights the key changes:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 18: Example 2</title>
<style>
.fieldname {
text-align: right;
}
.submit {
text-align: right;
}
</style>
</head>
<body>
<form>
<table>
<tr>
<td class="fieldname">
Username:
</td>
<td>
<input type="text" id="username" />