throw vs throws in Java

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