Difference between throw and throws in java
In my previous tutorials I’ve covered below topics. In this post we are going to discuss difference between throw and throws in Java. Below are the links of my tutorials on throw and throws. I would highly recommend you to go through the below tutorials so that it would be easy for you to understand these terms.
- Throw in Java
- Throws in Java
- throw keyword example
- throws keyword example
Throw vs Throws in java
1. Throws clause in used to declare an exception and thow keyword is used to throw an exception explicitly.
2. If we see syntax wise than throw is followed by an instance variable and throws is followed by exception class names.
3. The keyword throw is used inside method body to invoke an exception and throws clause is used in method declaration (signature).
for example.
Throw :
.... static{ try { throw new Exception("Something went wrong!!"); } catch (Exception exp) { System.out.println("Error: "+exp.getMessage()); } } ....
Throws :
public void sample() throws ArithmeticException{ //Statements ..... //if (Condition : There is an error) ArithmeticException exp = new ArithmeticException(); throw exp; ... }
4. By using Throw keyword in java you cannot throw more than one exception but using throws you can declare multiple exceptions. PFB the examples.
for e.g.
Throw :
throw new ArithmeticException("An integer should not be divided by zero!!") throw new IOException("Connection failed!!")
Throws :
throws IOException, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException
That’s all I have for this topic. Let me know if I missed any difference between throw and throws in Java. If you have any queries regarding it, please feel free to ask me. Just drop a comment below, I’ll try to answer as soon as possible.
Comments
Post a Comment