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): 26950/ 33

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

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-23 8:44:51 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search