Servlet Exception Handling


Prev Tutorial Next Tutorial

Exception Handling in Servlet

The process of converting system error messages into user friendly error message is known as Exception handling. This is one of the powerful feature of Java to handle run time error and maintain normal flow of java application.


An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's Instructions.

  • Programetically Exception Handling mechanism
  • Declarative Exception Handling mechanism

Programetically Exception Handling mechanism

The approach to use try, catch block in java code to handle exceptions is known as Programetically Exception Handling mechanism.


<form action="servlet1">
Name:<input type="text" name="userName"/> <br/>
<input type="submit" value="continue"/>

Exception Handling in Servlet

import javax.servlet.*;  
import javax.servlet.http.*;  
public class FirstServlet extends HttpServlet {  
  public void doPost(HttpServletRequest request, HttpServletResponse response){  
    PrintWriter out = response.getWriter();  
    String n=request.getParameter("userName");  
    out.print("Welcome "+n);  
    Cookie ck=new Cookie("uname",n);//creating cookie object  
    response.addCookie(ck);//adding cookie in the response  
    //creating submit button  
    out.print("<form action='servlet2'>");  
    out.print("<input type='submit' value='continue'>");  
        }catch(Exception e){System.out.println(e);}  

Declarative Exception Handling mechanism

The approach to use xml tags in web.xml file to handle the exception is known as declarative exception handling mechanism.

This mechanism is usful if exception are common for mote than one servlet program. In real time application this mechanism is widely use.


<p> Oooops....... page not found</p>  

import javax.servlet.*;
public class FirstServlet extends HttpServlet {  
  public void service(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException
   // get request parameter
   // business operation
   String resultvalue="<body bgcolor="cyan" text="red"> <h1> hello word</h1></body>";

   // prepare response
   printWriter out=resp.getWriter();

   // send response






Prev Tutorial Next Tutorial


Buy This Ad Space @$20 per Month, Ad Size 600X200 Contact on: or 9999595223

Pure VPN Privide Lowest Price VPN Just @ $1.65. Per Month with Non Detected IP Lowest Price Non Detected IP VPN

Magenet is best Adsense Alternative here we earn $2 for single link, Here we get links ads. Magenet

For Projects 9999595223

Google Advertisements

Buy Websites 9999595223

Buy College Projects with Documentation Contact on whatsapp 9999595223. Contact on: or 9999595223 Try this Keyword C++ Programs