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

Using throw and throws

The syntax for the usage of throw and throws clause is given below.

Listing 3

public void functionname throws exceptionclass
{
      ………
      ………
throw
      ………
      ………
}

Before catching an exception, some code should throw the exception first. An exception can be thrown by the code of the program, Java runtime environment, etc. One can use the exceptions defined in Throwable class or he can also create exceptions of his own.

Listing 4

class myException extends Exception
{
  int age;
  myException(int x)
  {
    age = x;
  }
  String toString()
  {
    return ("Age below requirement(" + age + ")");
  }
}
 
class exec
{
  public void vote(int x)throws myException
  {
    System.out.println("Voting condition ");
    if (x < 18)
      throw new myException(x);
    System.out.println("You are eligible to vote ");
  }
}
class demo
{
  public static void main(String a[])
  {
    exec obj = new exec();
    try
    {
      obj.vote(21);
      obj.vote(15);
      catch (myException e)
      {
        System.out.println("Error occured " + e);
      }
    }
  }

In the above example, toString() has been used. ToString() and getMessage() are the methods of every exception class. For the above program, an error occurs where we have passed 15 as the age, but for 21 the program executes successfully.


View Entire Article

Article Feedback

Title:  
Name:  
Url: ( Optional )
Comment:  
Please add 2 and 2 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-2008 ASPAlliance.com  |  Page Processed at 12/3/2008 8:27:19 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search