Difference between throw vs throws in Java

throw vs throws in Java
throw vs throws in Java programming Exceptionthrow and throws are two Java keyword related to Exception feature of Java programming language. If you are writing Java program and familiar with What is Exception in Java, its good chance that you are aware of What is throw and throws in Java. In this Java tutorial we will compare throw vs throws and see some worth noting difference between throw and throws in Java. Exception handling is an important part of Java programming language which enables you to write robust programs. There are five keywords related to Exception handling in Java e.g. try, catch, finally, throw and throws. Apart from difference between final, finally and finalize,  throw vs throws is one of the frequently asked Java interview question. Difference listed here will not only help you to answer this interview question but also understand concept behind throw and throws better.

1) throw keyword is used to throw Exception from any method or static block in Java while throws keyword, used in method declaration, denoted which Exception can possible be thrown by this method.

2) If any method throws checked Exception as shown in below Example, than caller can either handle this exception by catching it or can re throw it by declaring another throws clause in method declaration.

public void read() throws IOException{
   throw new IOException();

failure to either catch or declaring throws in method signature will result in compile time error.

3) throw keyword can be used in switch case in Java but throws keyword can not be used anywhere except on method declaration line.

4) As per Rules of overriding in Java, overriding method can not throw Checked Exception higher in hierarchy than overridden method . This is rules for throws clause while overriding method in Java.

5) throw transfers control to caller, while throws is suggest for information and compiler checking.

6) Both Checked and Unchecked Exception can be declared to be thrown using throws clause in Java.

That's all on difference between throw vs throws in Java and Exception handling. You must try some example to use throw and throws as well and rather importantly you must know when to use throw and throws keyword in Java. In summary use throw to actually throw exception which will give control back to caller and use throws to declare which Exception can be thrown by a particular method, which allows caller to handle them.

Other Java Tutorials from Java67 Blog

No comments:

Post a Comment