-4

I found an unfamiliar usage of "throws" in Android sample code like below.

public Void handleResponse(HttpResponse response) throws IOException
{
  ...
}

I just want to know how this "throws" works in this case. I posted this since it was a bit hard to find appropriate search word go google.

ldam
  • 4,412
  • 6
  • 45
  • 76
  • 3
    This is just Java, and should be covered by *any* beginner's Java book. Stack Overflow is great for specific problems, but it's really not suitable to learn a language from scratch - you should read a good book or tutorial. – Jon Skeet Jan 18 '13 at 13:24
  • http://bit.ly/VvEoJN Second link googling for "java throws keyword". – ldam Jan 18 '13 at 13:26

5 Answers5

3

I think you are mixing throws and throw.

throws indicates in the method's signature that it can throw an IOException in some cases. throw new IOException() will throw the actual exception.

The throws keyword can be seen in every Java program, and forces you to encapsulate your method call in a try {} catch(){} block if the exception is a checked exception

Bastien Jansen
  • 8,756
  • 2
  • 35
  • 53
1

The throws keyword after the method declaration indicates that this method might throw this exception. It means that any calling method must ensure that they catch this exception, like this:

...
try {
  var.handleResponse(response);
catch (IOException e) {
  // oops, something went wrong
  e.printStackTrace();
}
Stefan Seidel
  • 9,421
  • 3
  • 19
  • 18
  • Thanks Stefan. This is the first time to see "throws" keyword in declaration. And I understood it from your simple & nice explanation.Thanks! – user1990540 Jan 18 '13 at 22:31
0

somewhere in the body of the function handleResponse() there is a possibility of an IOException being thrown. when you call the function you will need to surround it in try..catch block.

David M
  • 2,511
  • 1
  • 15
  • 18
0

IOException is a checked Exception and therefore the throws IOException is required if your code inside the method can throw an IOException (and you are not catching it inside the method). This wouldn't be required if IOException would be a RuntimeException (like NullPointerException). Maybe you should have a look at this question.

Community
  • 1
  • 1
micha
  • 47,774
  • 16
  • 73
  • 80
0

You should start from the Java Tutorials. From the same tutorial:

All methods use the throw statement to throw an exception. The throw statement requires a single argument: a throwable object. Throwable objects are instances of any subclass of the Throwable class. Here's an example of a throw statement.

    throw someThrowableObject;
Swapnil
  • 8,201
  • 4
  • 38
  • 57