In this post we'll see the difference between throw and throws keyword in Java which are used in Java exception handling. These two keywords, though look similar, are functionality wise very different
- throw is used to throw an exception.
- throws is used to declare an exception, that can be thrown from a method, in the method signature.
throw Vs throws in Java
- We can declare multiple exceptions as a comma separated list with throws statement.
We can throw only one exception using throw keyword in Java.throws Example
public void displayFile() throws IOException, ArithmeticException
throw Example
throw new NullPointerException(); throw new FileNotFoundException();
-
throw keyword in Java is followed by an object of the Exception class.
throws is followed by exception class names themselves.throw Example
catch(FileNotFoundException fExp){ // throwing fExp which is an object of FileNotFoundException type throw fExp; }
// creating object and throwing throw new FileNotFoundException();
throws Example
public void displayFile() throws IOException, ArithmeticException
It can be seen that Exception class name itself is in the declaration.
throws clause in Java is used to declare an exception in the signature of the method where as throw keyword is used to throw an exception explicitly with in the code of the method or from a static block.
throw from a static block
static int i; static int b; static { System.out.println("in static block"); try{ i = 5; b = i * 5; }catch(Exception exp){ System.out.println("Exception while initializing" + exp.getMessage()); throw exp; } //System.out.println("Values " + i + " " + b); }
- throws clause is used to declare that the method may throw the declared exceptions and calling method
should provide the exception handling code.
throw actually throws the exception and the run time system goes through the method hierarchy to search for a method that can handle the exception.
That's all for this topic Difference Between throw And throws in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!
Related Topics
You may also like-
No comments:
Post a Comment