Home Jsp Use multiple catch statement in single jsp
Questions:Ask|Latest

 
 

Share on Google+Share on Google+

Use multiple catch statement in single jsp

Advertisement
In java a single try can have multiple catch statements. The code bound by the try block need not always throw a single exception so we can use multiple catches or Exception class (base class of all exceptions).

Use multiple catch statement in single jsp

     

In java a single try can have multiple catch statements. The code bound by the try block need not always throw a single exception so we can use multiple catches or Exception class (base class of all exceptions). When exception occurs while executing any statement within try block, control enters into the catch blocks until it finds its matching block.

If catch block containing the Exception class object then the subsequent catch blocks will not be executed. If the appropriate exception object is not found and Exception class is also not used in program, the java complier gives an error stating that the subsequent catch blocks have not been reached. This is known as Unreachable code problem. To resolve this, the last catch block in multiple catch blocks must contain the Exception class object.

The example below 'multi_catches_jsp.jsp' will show you how to use multiple catch blocks to handle multiple exceptions. This program encounters problem with arithmetic calculation , so throwing Arithmetic Exception. To handle any other type of exception which has not been handled, we have used catch block with Exception object.

multi_catches_jsp.jsp

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd"> 
<HTML>
    <HEAD>
        <TITLE>multiple catch in single jsp program</TITLE>
    </HEAD>
    <BODY>
	<% try {
		int arithmeticExp = 10/0;
       }
           // Multiple catch statement
	   catch(ArithmeticException aEx){
		   out.println("Arithmetic Exception : "+aEx);
	   }
	   catch(Exception ex){
		  out.println("Exception : "+ex);
	   }
	%>
    </body> 
</html>

Save this code as a .jsp file named "multi_catches_jsp.jsp" in your application directory ('user' in our example) in Tomcat server and run this jsp page with url http://localhost:8080/user/multi_catches_jsp.jsp in address bar of the browser.

Download Source Code

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: July 9, 2008

Related Tutorials

Ask Questions?    Discuss: Use multiple catch statement in single jsp  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com