Sunday 5 August 2012

Difference between throw and throws in Java?

Throw is used to actually throw the exception, whereas throws is used for specifying the exceptions thrown by a method .They are not interchangeable. 
public void myMethod(int param) throws MyException



   if (param < 10) 
throw new MyException("Too low!); 
      --------
}
The Throw clause can be used in any part of code where you feel a specific exception needs to be thrown to the calling method. 
If a method is throwing a checked exception, it should either be surrounded by a try catch block to catch it or that method should have the throws clause in its signature. Without the throws clause in the signature the Java compiler does not know what to do with the exception. The throws clause tells the compiler that this particular exception would be handled by the calling method.


Let us take one method divide, here we are throwing a user-defined exception if the second parameter is zero.



static int divide(int first, int second) {
if (second == 0)
throw new MyException("can't be divided by zero");
return first / second;
}


In the above method you can handle the exception in two ways.



1) surround the code with a try-catch block.



static int divide(int first, int second) {
if (second == 0)
try {
throw new MyException("can't be divided by zero");
} catch (MyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return first / second;
}



2)  add throws clause in the method signature 

If the divide method doesn't catch the checked exceptions that can occur within it, the divide method must specify that it can throw these exceptions. Let's modify the original divide method to specify the exceptions it can throw instead of catching them. 





static int divide(int first, int second) throws MyException {
if (second == 0)
throw new MyException("can't be divided by zero");
return first / second;
}


We can conclude the above discussion like this.The throw is used to actually throw the exception whereas throws is used for specifying the exceptions thrown by a method.

No comments:

Post a Comment