Home > Articles

Handling Exceptional Conditions

Had the user entered an invalid year, a sight equivalent to the "blue screen of death" would flash before the user's eyes. Figure 3.5 displays the output in the browser had the user entered "aaaa" for the year:

Figure 3.5 shows an exception that occurred in the JSP indicating that the parseInt method couldn't parse the data. The exception is propagated to the user in case there are no error-handling routines. Such sights could rattle visitors to your site or users of your application, so much so that that they might never visit it again.

Figure 3.5 A Runtime Exception propagated to the browser

There are different ways to prevent and handle such exceptional conditions. You might want to use some or all of the following mechanisms:

  • Using error pages

  • Performing client-side validations using a scripting language

  • Performing server-side validations in the JSP

Using Error Pages

In the event of an exception occurring on the server side, you might want to gracefully exit by specifying error pages for your JSPs. When exceptions occur within the JSP, the JSP container will automatically redirect to the error page. Error pages will trap arbitrary runtime exceptions and are good indications of bugs in the program.

You need to create an error page, error.jsp, that displays a generic error as shown in Listing 3.7.

Listing 3.7 error.jsp: Displaying a Generic Error Message

<%@ page isErrorPage="true" %>
<html>
<head>
 <title>Oops!</title>
</head>
<body>
<h1>We are sorry</h1>
The page you have just reached has some errors.
Our technical staff has been informed of the error and will fix it 
as soon as possible.
<p>
Error: <%= exception.getMessage() %>
<p>
Thank you for your patience
</body>
</html>

To specify error.jsp as the error page for JSPs, modify page directives to include the errorPage parameter:

<%@ page import="java.util.*, java.text.DateFormat" errorPage="error.jsp" %>

Figure 3.6 shows the error page as displayed in a browser when the user inputs an invalid year.

Figure 3.6 The Error Page displayed on an error

You can enhance the error JSP to send an email informing the support staff about the error as shown in the next chapter. In this way they can take corrective action to fix the bug.

Performing Client-Side Validations Using JavaScript

The second approach to preventing such an erroneous situation from occurring is to nip it at its bud. You can embed validation routines in your input page defined using a client-side scripting language. This way the user's data can be checked before being sent to the server, and also reduce network traffic by preventing roundtrips from the server.

Most browsers today support at least one client-side scripting language, with JavaScript being the most popular among them all. You can create routines using these scripting languages to check whether the data supplied by the user is valid, and alert the user of the mistake right away, without having to send the request with the incorrect data to the server.

JavaScript enables you to access different elements of your document using the Document Object Model and also provides some methods to operate on basic data types.

The Document Object Model provides a programmatic access to the document. Each element of the document is a part of the hierarchy with the window containing the document as the root. In JavaScript such elements are known as Navigator Objects.

You can access and update each Navigator Object in the document with JavaScript by using its location within the hierarchy. For example, to retrieve the title of the document being displayed in the window, you can use document.title. To access the value of the month input field within the form named monthform you can use document.monthform.month.value in your JavaScript routine.

In Listing 3.8, the Submit button has been replaced with a JavaScript enhanced button. It defines a handler for the onClick method passing the form in which the event occurred as a parameter. The validation method extracts the value of the year field, parses it, and checks if the number obtained from that operation is a valid one. If it is not valid, determined from the return value of the isNan() operation, it opens an alert window displaying the error message as shown in Figure 3.7. If it is valid, it submits the form to the server. No checks need to be done for the month field because the input is constrained to the values displayed in the drop-down list.

Figure 3.7 Alert displayed using JavaScript on an invalid input

Listing 3.8 input.jsp: Validation Routine Written in JavaScript

<html>
<head>
 <title>Calendar Input Page</title>
<script language="JavaScript">

<!-- Hide script from old browsers
function validate(f) {
 intValue = parseInt(f.year.value);
 if (isNaN(intValue)) {
 alert("Please enter a valid year");
 return false;
 }
 else {
 f.submit();
 }
}
// End hiding -->

</script>
</head>
<body>
 <center><h1>Calendar Viewer</h1></center>
 <table border=0 WIDTH="500" >
 <tr>
  <td></td>
  <td width="80%"><font size=+2>Overview</font> <br>Provide the Month
  and Year andclick on the Submit button to view the Calendar for 
  the Month. <p><br>
  <form method="get" action="month.jsp" name="monthform"
   onSubmit="validate(this)">
  <table border="0" >
  <tr>
   <td width="40%"><b>Month:</b></td>
   <td><select name="month">
    <option value="0">January</option>
    <option value="1">February</option>
    <option value="2">March</option>
    <option value="3">April</option>
    <option value="4">May</option>
    <option value="5">June</option>
    <option value="6">July</option>
    <option value="7">August</option>
    <option value="8">September</option>
    <option value="9">October</option>
    <option value="10">November</option>
    <option value="11" selected="true">December</option>
   </select></td>
  </tr>
  <tr>
   <td><b>Year:</b></td>
   <td><input type="text" name="year" size="20" maxlength="4">
   </td>
  </tr>
  </table>
  <br><p>
  <input TYPE="button" NAME="Submit" VALUE="Submit"
   onClick="validate(this.form)">
  <input TYPE="reset" NAME="Reset" VALUE="Reset">
  </form></td>
 </tr>
</table>
</body>
</html>

NOTE

You should provide the onSubmit handler in the form tag as well. This allows the browser to validate the form data when the user submits the form by hitting the Enter button.

Performing Server-Side Validations

Client-side validations aren't always the recommended error-handling mechanism because of the following reasons:

  • The browser might not support JavaScript. Older browsers might not support any scripting languages.

  • The user might have disabled the feature.

  • If the GET request method is being used, the user can set the value of the parameters by altering the URL, thus bypassing the validation routines as shown in Figure 3.8.

Figure 3.8 Manually specifying the parameters by altering the URL in the browser

You should validate the user values within the JSP and should process the values only if they have passed the validation. In the monthly calendar JSP, you should check whether the month and year provided by the user are valid integral values. You should also provide the user with feedback about the data and the mistakes in them that they provided.

Let's alter the scriptlet that reads the request parameters and initializes the java.util.Calendar instance. First, you need to create a declaration for a string representing the message you want to send across to the user when an invalid year is specified. Now enclose the potentially troublesome code within a try-catch block. In this case it's when you parse the year string to its integral equivalent.

If the operation results in an exceptional condition, forward the request to the input JSP, passing the error message as a parameter, so that the user can retry sending the information. In the JSP forward tag you need to specify the name of the JSP to which the request needs to be redirected, input.jsp in this case. You can also specify additional parameters, such as the error message for the year field, yearMsg, and the error message for the month field, monthMsg.

The JSP forward tag can not be included within the scriptlet, hence the scriptlet needs to be divided into two parts, as shown in Listing 3.9:

  • For parsing the request parameters and catching the exceptions.

  • For closing the if block in the previous scriptlet and for setting the values in the calendar instance.

Listing 3.9 input.jsp: Validation Routine in the JSP

<%! public final static String INVALID_YEAR = "Please enter a valid year," +
  " without any spaces, alphabets and special characters";
 public final static String INVALID_MONTH = "Please enter a valid month"; %>
<%
 int month = -1;
 int year = -1;
 String monthError = "";
 String yearError = "";
 try { month = Integer.parseInt(request.getParameter("month"));
 } catch Exception exc) {
  monthError = INVALID_MONTH;
 }

 // Validate the year
 try {
  year = Integer.parseInt(request.getParameter("year"));
 } catch (Exception exc) {
  yearError = INVALID_YEAR;
 }

 if (!(monthError.length() == 0 && yearError.length() == 0)) {
%>

 <jsp:forward page="input.jsp">
 <jsp:param name="yearMsg" value="<%= yearError%>"/>
 <jsp:param name="monthMsg" value="<%= monthError%>"/>
 </jsp:forward>

<% }
 cal.set(year, month, 1);
%>

You also need to alter input.jsp to allow the error message to be displayed. Input.jsp will be used for accepting the first time input as well as for the retries.

The error message that was passed as a parameter in the forward tag can be obtained just like any other request parameter from the 'request' implicit object by specifying the parameter name.

A good place to display the error message in a Web document is next to the source itself. Displaying the error message in a different color allows the user to notice the message. You can add the error message for the year next to the year label and display it with a red color to highlight the problem as shown in Listing 3.10.

Listing 3.10 input.jsp: Validation Routine in the JSP

<tr>
 <td><b>Year:</b><br>
 <font color="red" size="-2">
 <% 
  String yearMsg = request.getParameter("yearMsg");
  out.println(((yearMsg == null) ? "": yearMsg));
 %>
 </font>
 </td>
 <td valign="top">
 <input type="text" name="year" size="20" maxlength="4">
 </td>
</tr>

You might also want to set the valid values within the input.jsp so the user doesn't have to enter it again. Earlier, you saw how the options for the menu could be generated dynamically by using a scriptlet. You need to enhance the scriptlet to allow the option representing the valid month to be selected in the drop-down list as shown in Listing 3.11.

Listing 3.11 input.jsp Enhancing the Generate Month Options Scriptlet to Display Existing Selections

<%! String[ ] monthNames = (new DateFormatSymbols()).getMonths(); %>
<% 
 int month = 11;
 try {
 month = Integer.parseInt(request.getParameter("month"));
 } catch (Exception exc) {
 }

 // Print all the options
 for (int i = 0; i < 12 ; i++) {
 out.print("<option value=\""+ i + "\"");
 if (i == month) {
  out.print(" selected=\"true\"");
 }
 out.println(">" + monthNames[i] + "</option>");
 } // end for-loop
%>

Figure 3.9 shows the error message displayed in the input page when an incorrect year is specified.

Figure 3.9 The Revamped Input Page displaying error information

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020