Skip to content Skip to sidebar Skip to footer

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 a

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


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


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


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


Post a Comment for "How Do I Override A Class Method In Java And Add A "throws" Declaration To It?"