0

I have the following code to pass an IP to some package that looks up the country.

WebServiceClient client = new WebServiceClient.Builder(42, "license_key").build();
InetAddress ipAddress = InetAddress.getByName("128.101.101.101");
CountryResponse response = client.country(ipAddress);

The problem is, that this gives me the error:

unreported exception UnknownHostException; must be caught or declared to be thrown

What am I doing wrong?

2
  • Well, the compiler tells you what you are doing wrong; you have to handle the exception. Commented Dec 20, 2014 at 21:59
  • Place it in the try catch block so the exception is handled properly Commented Dec 20, 2014 at 22:01

1 Answer 1

1

One of those functions (at least) declares that exception as throwable. In Java, all declared throwable exceptions must be caught- you don't need to do anything in the exception handler (although logging it at least is a good idea), but it has to be there, or the function that calls it must also declare those exceptions as throwable (and its caller would then need to catch them). Its a mechanism in Java called "checked exceptions". A lot of people don't like them and many consider it to be a mistake, but those parts of the Java library that use it will probably never change, so you have to live by the rules.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.