简体   繁体   English

如何在Java中覆盖类方法并向其添加“throws”声明?

[英]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? 难道在Android中有一个“抛出”东西的AsyncTask吗? If I don't @Override the method, it doesn't get called. 如果我不@Override方法,它不会被调用。 If I add the "throws" at the end, there are compiler errors. 如果我在末尾添加“throws”,则会出现编译器错误。 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. json.getJSONObject抛出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). 您需要做的是使用运行时(未检查)异常(通常类似于IllegalArgumentException ;或者如果没有匹配语义,普通RuntimeException )来包装异常,并将已检查的异常指定为“根本原因”(通常作为构造函数参数)。

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). 不,你不能扩大一组检查异常:这将违反基本的OO原则,类似于你不能降低可见性(例如从公共到私有)。

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. 感谢Time4Tea,我能够在出现错误时调用的类中添加回调方法。 For example: 例如:

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

Where onJsonException is the class callback method. 其中onJsonException是类回调方法。

You can't override methods in such way. 您不能以这种方式覆盖方法。

In your case the solution is to add try-catch block and return false. 在您的情况下,解决方案是添加try-catch块并返回false。 Also you can add a String field tou your task and fill it with error description. 您还可以添加一个String字段来填充您的任务,并填写错误说明。 Then you can use it in onPostExecute() method. 然后你可以在onPostExecute()方法中使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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