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


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>
   <head>
      <title>Try...Catch Example</title>
   </head>
   <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

182 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements