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): 26951/ 35

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

User Comments

Title: exception handling   
Name: sireesha
Date: 2011-03-09 11:17:54 AM
Comment:
very nice notes.
Title: very effective   
Name: bindu
Date: 2010-12-27 2:37:02 AM
Comment:
the article is very clear and effective
Title: good   
Name: anil
Date: 2008-05-14 4:51:03 AM
Comment:
it's every one easy understand
Title: compact   
Name: Sharon
Date: 2007-10-03 1:39:57 AM
Comment:
The discernment of the topic was quite applicable
Title: Great   
Name: Abhas
Date: 2007-08-27 11:47:42 AM
Comment:
Your style of writing articles is just great
Title: Good work   
Name: John
Date: 2007-08-21 11:27:32 AM
Comment:
Keep up the good work

Product Spotlight
Product Spotlight 





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


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-24 12:03:52 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search