throw is used to throw an exception manually, where as throws is used in the
case of checked exceptions, to reintimate the compiler that we have handled the
exception. so throws is to be used at the time of defining a method and also at
the time of calling that function, which rises an checked exception.
Prog. to explain diff. b/w throw and throw:
class MyException extends Exception //to create our own exception
{
public String toString() //overriding the method toString() to print the
desired msg.
{
return "Can not divide a no. with one: "+"MyException";
}
public static void main(String args[]) throws MyException //use of throws
{
int a=Integer.parseInt(args[0]);
int b=Integer.parseInt(args[1]);
if(b==1)
throw new MyException(); // rises an MyException, if we try to divide a no.
with 1
else
System.out.println((float)a/b);
}
}
if we want to rise our own exception, we have to use either throws or to handle
the exception by try-catch. if not, it gives the compile time error.
and throw is to rise the exception manually, In the above prog. I rised an
exception when you try to divide a no with 1.(own Exception)
----- Original Message -----
From: Anurag Walia
To: [email protected]
Sent: Thursday, February 05, 2009 1:05 PM
Subject: [java programming] difference between throw and throws
hello
i want to know about the difference between throw and throws clearly?
--~--~---------~--~----~------------~-------~--~----~
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/javaprogrammingwithpassion?hl=en
-~----------~----~----~----~------~----~------~--~---