# Can we write code in try/catch block in JSP as well?

JSPJava 8Object Oriented ProgrammingProgramming

#### Learn Complete Java - Core Java, JSP & Servlets

240 Lectures 30 hours

#### JSP, Servlet, JSLT + Hibernate: A complete guide

108 Lectures 11 hours

#### Full Stack Java developer - Java + JSP + Restful WS + Spring

Best Seller

517 Lectures 57 hours

If you want to handle errors within the same page and want to take some action instead of firing an error page, you can make use of the try....catch block.

Following is a simple example which shows how to use the try...catch block. Let us put the following code in main.jsp −

<html>
<title>Try...Catch Example</title>
<body>
<%
try {
int i = 1;
i = i / 0;
out.println("The answer is " + i);
}
catch (Exception e) {
out.println("An exception occurred: " + e.getMessage());
}
%>
</body>
</html>

Access the main.jsp, it should generate an output somewhat like the following −

An exception occurred: / by zero
Updated on 30-Jul-2019 22:30:25