Hi
we want to know that What is the difference between throw and throws clause, explain programmatically
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Satyapriya NayakPosted Jun 3, 2012, 1:19 AM
A program can throw an exception, using throw statement. When an exception is thrown, normal execution is suspended. The runtime system proceeds to find a catch block that can handle the exception. The exceptions are caught under the Exception class. This class is used for giving user defined exception. To use this class throw keyword is used.
//Program using throw keyword
class check_age extends Exception// inheriting the exception class
{
public String toString()
{
return "Age cannot be less than 18";
}
static void age(int a)
{
try// to handle exception try and catch block is given
{
if(a<18)
{
check_age obj= new check_age();
throw obj;// throwing exception using class object
}
else
System.out.println("Adult");
}
catch(Exception e)// catch block to give error message
{
System.out.println(e);
}
}
public static void main(String args[])
{
age(Integer.parseInt(args[0]));
}
}
However if the user wants to handle the Exception at some point like in other class then the Java provides with the throws statement.
class check_age extends Exception// inheriting the exception class
{
public String toString()
{
return "Age cannot be less than 18";
}
}
class a
{
static void age(int a)throws Exception
{
if(a<18)
{
check_age obj= new check_age();
throw obj;
}
else
System.out.println("Adult");
}
public static void main(String args[])
{
try
{
a obj1=new a();
obj1.age(Integer.parseInt(args[0]));
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Thanks