Difference in throw and throws in Java

Price: INR 8,999.00
Price: INR 15,999.00
Was: INR 16,999.00

Let’s see What is Difference in throw and throws in Java. throw keyword and throws keyword both are related to Exception Handling in Java.

The main difference between throw and throws is in their usage and functionality. where throws is used in method signature to declare Exception possibly thrown by any method, the throw is actually used to throw Exception in Java code.

 

Difference in throw and throws in Java

We can understand this with simple code example.

If you see the code above, throws keyword is used to declare Exception thrown by this method shutdown(), by looking at method signature we know that it’s throwing IOException. while inside method code throw keyword is actually used to throw an instance of IOException.

 

Selenium Testing Video Tutorial:

 

 

Let’s see the differences between throw and throws keyword –

  • Throws clause in used to declare an exception and throw keyword is used to throw an exception explicitly.
  • You can declare multiple exceptions thrown by method in throws keyword by separating them in common e.g. throws IOException, ArrayIndexBoundException etc
    while you can only throw one instance of exception using throw keyword e.g. throw new IOException(“not able to open connection”).
  • The keyword throw is used inside method body to invoke an exception and throws clause is used in method declaration (signature).
  • throws keyword gives a method flexibility of throwing an Exception rather than handling it. On the other hand, throw keyword transfer control of execution to the caller by throwing an instance of Exception.
  • throws keyword cannot be used anywhere exception method signature while throw keyword can be used inside the method or static initialize block provided sufficient exception handling.
  • throw keyword can be used in switch case in Java but throws keyword can not be used anywhere except on method declaration line.
  • throw transfers control to the caller while throws are suggest for information and compiler checking.
  • As per Rules of overriding in Java, overriding method can not throw Checked Exception higher in the hierarchy than overridden method . This is rules for throws clause while overriding the method in Java.

 

0 Comment

Leave a Reply