JSP is very mature about handling errors. JSP use Exception handling classes for dealing with error. Every program or code can throw an error; to rectify these errors should know what real problem is. These error classes in JSP tell us what exact problem is where we have to do modify in our code to remove error. This give us detail and deep information of error, can be display on particular error page or put it in error object System.err.
JSP provide try catch block to hand run time exception. JSP have property in
<%@ page isErrorPage="true" %>
<%@ page language="java" errorPage="error.jsp" %>
try catch block is important feature to caught exception in JSP page, do according to programmer specification.
Example of try catch Error Handling in JSP
tryCatch.jsp
<%@ page language="java" errorPage="" %>
<html>
<head>
<title>Error Handling by try catch block in JSP</title>
</head>
<body>
<%
try{
int a=0;
int b=10;
int c=b/a;
}
catch(Exception e)
{
e.printStackTrace(); /// This will give detail information of error occur
out.print("Error caught by Catch block is : "+e.getMessage());
}
%>
</body>
</html>
This will show
Error caught by Catch block is :/ by zero
java.lang.ArithmeticException: / by zero, a number can be division by zero digits; it is caught by arithmeticException and prints this error.
e.printStackTrace(); give us detail error information and can see at tomcat console mode or at logs folder in catalina.out file.
Sometimes error handling is useful when we are inserting user data into a registration table with unique field of UserId. If we enter duplicate UserId, sqlException will throw a duplicate row field error. User can know, this UserId is already exists in database.
JSP can use customized error page by setting errorPage="error.jsp".
Example of Error page in JSP
errorPage.jsp
<%@ page language="java" errorPage="" %>
<html>
<head>
<title>Error Handling by try catch block in JSP</title>
</head>
<body>
<%
try{
int a=0;
int b=10;
int c=b/a;
}
catch(Exception e)
{
e.printStackTrace(); /// This will give detail information of error occur
out.print("Error caught by Catch block is : "+e.getMessage());
}
%>
</body>
</html>
second page is error page
error.jsp
<html>
<head>
<title>Caught Error in JSP Page</title>
</head>
<body>
Error is found on this page(This is own customized error page)
</body>
</html>
|