0

I have a super simple line:

JSONObject params = new JSONObject("{\"values\": { \"barcode\": \"testing\" } }");

Android studio tells me that this line 'throws JSONException', but why? I must be doing something stupid here. Any help is appreciated

3
  • 1
    Does it actually throw the exception at runtime (if so, what is the error message) or is this just a compile-time error (asking you to catch or rethrow a JSONException that might happen)? Commented Jan 3, 2016 at 4:10
  • @Thilo this is a compile time error Commented Jan 3, 2016 at 4:10
  • That JSONObject constructor has the possibility to throw that error so you need to deal with it (catch) even when you know "it can't happen". Commented Jan 3, 2016 at 4:13

2 Answers 2

3

JSONException is a checked exception. This means that you need to have code in place to deal with it. You need to either catch the exception or let it bubble up by declaring throws JSONException on your method.

This is the case for all checked exceptions in Java (all exception except those that extend RuntimeException).

In your case, since the String is constant and correct, I would do

   } catch ( JSONException e) {
      // should never happen
      throw new IllegalArgumentException("unexpected parsing error",e);
   }

This will convert the JSONException (if for some reason it does happen after all) into an (unchecked) RuntimeException.

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

Comments

1
public JSONObject(String source) throws JSONException {
        this(new JSONTokener(source));
    }

You are using above method/constrcutor to create your JSONObject and its saying in its signature that it throws JSONException so you can't simply do what you have done ,

JSONObject params = new JSONObject("{\"values\": { \"barcode\": \"testing\" } }");

You need to enclose above line in Java try- catch since method signature is clearly specifying a checked Exception so you need to handle that in try catch.

try{
JSONObject params = new JSONObject("{\"values\": { \"barcode\": \"testing\" } }");

}catch(JSONException ex){
 //eat or rethrow your exception
}

You have to note that there are other JSONObject constructors which doesn't specify any checked exceptions so you can use those in a simple line, like you did but the one you are trying to use specifies a checked exception so you need to handle that - otherwise your code won't compile.

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.