Exception Handling in Java
page 3 of 5
by Debjani Mallick
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 8322/ 101

Using try, catch and finally

The syntax for the usage of try, catch and finally block is given below.

Listing 1

try
{
      ………
      ………
}
catch(exceptionclass obj1)
{
      ………
      ………
}
catch(exceptionclass obj2)
{
      ………
      ………
}
finally
{
      ………
      ………
}

For using an exception handler in an application, the first step we need to do is to enclose the code that is likely to generate an exception inside a try block. If an exception occurs in the try block then it is handled by the exception handler associated with it. For associating an exception handler to the try block, we need to have one or more catch blocks after the try block where each catch block acts as an exception handler and can handle the type of exception indicated by its arguments. Exception handlers can be used to print an error message when an exception occurs, to halt the program, to redirect the error to a higher level handler using chained exception, to write code for recovering from the error, etc. The finally block is the block which is always executed when the try block exits which ensures that the finally block is executed even when an unexpected exception occurs. It acts as the appropriate place for writing the clean up code.

Listing 2

class exceptionDemo
{
  Random r = new Random();
  int a = r.nextInt();
  int b = r.nextInt();
  int c = r.nextInt();
  try
  {
    c = a / b / c;
    System.out.println("Value of c " + c);
  }
  catch (ArimeticException e)
  {
    System.out.println("The error is " + e);
  }
}

View Entire Article

Article Feedback

Title:  
Name:  
Url: ( Optional )
Comment:  
Please add 3 and 1 and type the answer here:

User Comments

Title: good   
Name: anil
Date: 5/14/2008 4:51:03 AM
Comment:
it's every one easy understand
Title: compact   
Name: Sharon
Date: 10/3/2007 1:40:43 AM
Comment:
The discernment of the topic was quite applicable
Title: compact   
Name: Sharon
Date: 10/3/2007 1:39:57 AM
Comment:
The discernment of the topic was quite applicable
Title: Great   
Name: Abhas
Date: 8/27/2007 11:47:42 AM
Comment:
Your style of writing articles is just great
Title: Nice one   
Name: Kin
Date: 8/24/2007 12:54:47 PM
Comment:
Go on
Title: Good work   
Name: John
Date: 8/21/2007 11:27:32 AM
Comment:
Keep up the good work

Product Spotlight
Product Spotlight 
Learn More
.NET Tools
asp.net shopping cart
asp.net chart control






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2009 ASPAlliance.com  |  Page Processed at 1/8/2009 9:10:15 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search