简体   繁体   中英

How do I override a class method in Java and add a “throws” declaration to it?

Would it be at all possible to have an AsyncTask in Android which "Throws" things? If I don't @Override the method, it doesn't get called. If I add the "throws" at the end, there are compiler errors. For example, I want to do something like:

class testThrows extends AsyncTask<String,Void,JSONObject> {
   @Override
   protected JSONTokener doInBackground(<String>... arguments) throws JSONException {
      String jsonString = arguments[0];
      JSONTokener json = new JSONTokener(jsonString);
      JSONObject object = json.getJSONObject("test");
      return object;
   }
}

json.getJSONObject throws a JSONException. Is there any way to do this?

What you need to do is to wrap the exception with a runtime (unchecked) exception (usually something like IllegalArgumentException ; or if nothing matches semantics, plain RuntimeException ), and specify checked exception as "root cause" (usually as constructor argument).

And no, you can not broaden set of checked exception: this would be against basic OO principles, similar to how you can not lower visibility (from public to private for example).

You can't override and throw more exceptions; you can only keep the signature as is or throw fewer exceptions.

You can throw unchecked exceptions; those don't change the method signature.

You cannot do this. Thanks to Time4Tea, I was able to add callback methods to the class that get called when there is an error. For example:

try {
   JSONTokener json = new JSONTokener(stringToJsonify);
   JSONObject object = json.getJSONObject("test");
} catch (JSONException e){
   onJsonException();
}

Where onJsonException is the class callback method.

You can't override methods in such way.

In your case the solution is to add try-catch block and return false. Also you can add a String field tou your task and fill it with error description. Then you can use it in onPostExecute() method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM