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

做~自己de王妃 提交于 2019-12-10 21:14:55

问题


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?


回答1:


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).




回答2:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/4660976/how-do-i-override-a-class-method-in-java-and-add-a-throws-declaration-to-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!