Martin
Martin

Reputation: 24318

Java/android: Help understanding this construct, is it a method or anonymous class?

I have been working with a library and I notice the following construct.

String run(String url) throws IOException {
  Request request = new Request.Builder()
      .url(url)
      .build();

  Response response = client.newCall(request).execute();
  return response.body().string();
}

I am having difficulty in identifying if it is an anonymous class as I don't see it using the interface or concrete class.

Or is it a just a normal method that does a throws IOException.

I am coming from a different programming background and looks kind of strange for me.

Are you forced to use throws ?

Upvotes: 0

Views: 64

Answers (2)

Mifeet
Mifeet

Reputation: 13618

If you are asking about the presence of throws IOException, you must declare it using the throws keyword, because it is a checked exception.

So basically

String       run    (String url) throws IOException { ... }
^            ^       ^           ^ 
method       method  param type  marks checked        ^
return type  name    and name    exceptions the       method body
                                 method may throw

Basically, checked exception in Java is any subclass of Throwable which does not inherit from RuntimeException or Error. Whenever your code throws a checked exception, the Java compiler forces you to either catch it or declare it using the throws keyword.

Checked exceptions allow you to verify at compile time that you are either handling exceptions or declaring them to be thrown: When you call a method like run(), the compiler will warn you that you must do something about it (catch or declare). For some explanation why Java enforces this, see e.g. this question on SO.


The article linked above explains what is the semantical difference between checked (e.g. NullPointerException) and unchecked exceptions (e.g. IOException)

Unchecked runtime exceptions represent conditions that, generally speaking, reflect errors in your program's logic and cannot be reasonably recovered from at run time

Checked exceptions represent invalid conditions in areas outside the immediate control of the program (invalid user input, database problems, network outages, absent files)

Upvotes: 3

sonic
sonic

Reputation: 1904

It is a method.

The signature of the method is String run(String url) throws IOException. It means that the method name is run; that the method take a String as argument; return another String and may throw an IOException.

Upvotes: 1

Related Questions