หากคุณต้องการจัดการข้อผิดพลาดภายในหน้าเดียวกันและต้องการดำเนินการบางอย่างแทนการเริ่มหน้าข้อผิดพลาด คุณสามารถใช้ 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