1

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

Rajendra_Prasad
  • 1,300
  • 4
  • 18
  • 36

4 Answers4

3

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
    }

}
Pratik
  • 30,639
  • 18
  • 84
  • 159
3

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.

a3.14_Infinity
  • 5,653
  • 7
  • 42
  • 66
3

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

Ankit
  • 6,554
  • 6
  • 49
  • 71
3

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.

4b0
  • 21,981
  • 30
  • 95
  • 142