我们能否在 JSP 中的 try/catch 块中编写代码?


如果你想在同一页面处理错误,并且希望采取一些操作而不是引发错误页面,你可以使用 try....catch 块。

下面是一个简单的示例,显示了如何使用 try...catch 块。让我们把下面的代码放在 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>

访问 main.jsp,它应生成类似以下内容的输出 −

An exception occurred: / by zero

更新于: 30-Jul-2019

230 浏览

开启你的 职业

完成课程以获得认证

开始
广告
© . All rights reserved.