我們能否在 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 瀏覽

開啟你的 職業

完成課程以獲得認證

開始
廣告