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.