Exceptions
what is the difference between throw and throws exception in java, how they are used?Explain with some example.
1 Answer
Know the answer? Post it. Somebody with the same question will find it here.
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Arpit JainRank #231 · 10.7K reputationPosted Aug 25, 2013, 6:48 AM EDT
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