How to override a class method in Java and add a throws declaration to it?

Was it even possible to have an AsyncTask on Android that throws things? If I do not use the @Override method, it will not be called. If I add throws at the end, there will be 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?

+3
source share
4 answers

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

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

Where onJsonException is the class callback method.

0
source

, ( , - IllegalArgumentException , plain RuntimeException)) "" ( ).

, : OO, , (, ).

+6

; .

; .

+3
source

You cannot override methods this way.

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

-1
source

Source: https://habr.com/ru/post/1784791/


All Articles