Difference between throw and throws in Java?

  1. throws clause is used to declare an exception and throw keyword is used to throw an exception explicitly.
  2. If we see syntax wise then 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
throw new Exception("You have some exception")
throw new IOException("Connection failed!!")
throws
public int myMethod() throws IOException, ArithmeticException, NullPointerException {}
  1. You cannot declare multiple exceptions with throw. You can declare multiple exception e.g. public void method()throws IOException,SQLException.
  2. checked exceptions can not be propagated with throw only because it is explicitly used to throw an particular exception. checked exception can be propagated with throws.

Comments