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 the difference between final, finally and finalize,  throw vs throws is one of the frequently asked Java interview questions. 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 the method declaration, denoted which Exception can possibly be thrown by this method.

2) If any method throws checked Exception as shown in below Example, then caller can either handle this exception by catching it or can re-throw it by declaring another throws clause in the 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 the hierarchy than overridden method . This is rules for throws clause while overriding a method in Java.

5) throw transfers control to the caller while throws are 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 the 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 an exception which will give control back to the caller and use throws to declare which Exception can be thrown by a particular method, which allows the caller to handle them.

Further Learning
Data Structures and Algorithms: Deep Dive Using Java
Java Fundamentals: The Java Language
Complete Java Masterclass

Other Java Tutorials from Java67 Blog

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.