Throw vs Throws in java
1. Throws clause in used to declare an exception and throw 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 andthrows clause is used in method declaration (signature).
for e.g.
Throw:
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