can anyone brief about difference between throws
and throw
in Exception handling in Java

- 1,300
- 4
- 18
- 36
-
2Well, what has your research shown so far? What documentation have you read? – Jon Skeet Apr 02 '13 at 05:45
-
1Maybe you can google it first...:) – Iswanto San Apr 02 '13 at 05:45
-
1refer this http://wiki.answers.com/Q/What_is_the_difference_between_throw_and_throws_in_Java – Dhinakar Apr 02 '13 at 05:49
4 Answers
throws was used when your method have some code which cause the error at run time and you need to handle or throws that exception when your method was calling.
While throw was for you can explicitly throw an error.
here is the example for both
For throws
public void test() throws ClientProtocolException,IOException{
HttpGet httpGet = new HttpGet(urlStr);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(httpGet);
}
this will throws the exception as ClientProtocolException or IOException whenever it cause.
For throw
public void test(String str){
if(str==null){
throw new NullPointerException(); // now here you explicitly throws the error whenever you getting str object as null
}
}

- 30,639
- 18
- 84
- 159
When we say: function() throws IOException, it means that the code inside the function is capable of throwing an IOException. So whoever is calling this function should handle this function in a try-catch block. So here we see the concept of checked exceptions.
When we say:
throw IOException.
Your code-block is deliberately throwing this exception and someone needs to catch it.

- 5,653
- 7
- 42
- 66
throws :
It simply passes the exception to the caller method. Also is an indicator that the method has possibility of throwing some exception while running, like IOException
, SQLException
etc... In case of checked exception (anything other than RunTimeException
or its subclass) It becomes mandatory to handle (try-catch) or again pass to caller.
throw:
it is the clause to generate the exception. (in simple words ) It is the reason why you see throws
in method signature, because they must have any throw
declaration inside them

- 6,554
- 6
- 49
- 71
We use throws
in a method signature to indicate that a method is capable of throwing a particular exception. Any code calling this method will have to deal with the possibility that particular exception can occur.
The throw
keyword is used to actually throw an exception. It can be used wherever you can place a statement.

- 21,981
- 30
- 95
- 142