Exceptions
what is the difference between throw and throws exception in java, how they are used?Explain with some example.
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.
Arpit JainPosted Aug 25, 2013, 10:48 AM
Syntax:throw exception_name_to_throw;
Throws is use for providing the security to calee function. If we use throws with any function then it means that function can not be called until calee makes proper arrangement of handling the exception thrown by the function to call.
Snatax: function_name() throws Exception_name {
...rest of the function code...
}
It is mandatory to catch exception thrown by Throw and Throws.
Example:
class test extends Exception{
public static void main(String args[]) throws Exception{
//demo of throw
int x=0;
throw new Exception("Throw demo"); //Comment this line for throws demo and uncomment the throws demo section
//Throws demo
// try{
// useThrows(); // this call is possible only from try block.
// }catch(Exception e){
// System.out.println(e.toString());
// }
}
static void useThrows() throws Exception{
//it is mandatory to call me from try and catch block only.
int x= 5/0;
}
}
Live Demo:
http://ideone.com/DHhjVx