2

When I try to throw to exception from onFailure method Android Studio forces me to add try catch block and not allowing to throw exception to calling function.

protected void createUser(final UserRegister user) throws ApiException, RuntimeException {

    Call call = dbApi.registerUserAsync(user, new ApiCallback<UserRegistered>() {
        @Override
        public void onFailure(ApiException e, int i, Map<String, List<String>> map) {
            Timber.e("Exception in createUser: " + e.getMessage());
            throw e;
        }
Nikhil
  • 91
  • 1
  • 7
  • It's because you are overriding the `onFailure` method, and it doesn't throw an exception to begin with. Try adding `throws ApiException` to `onFailure` and read the error. – Suleyman May 03 '18 at 21:25
  • Yeah tried that Android studio doesn't allow to add throws ApiException to onFailure method – Nikhil May 03 '18 at 21:31
  • Exactly, so the error explains why Android "forces" you to add a try/catch block and doesn't allow you to throw an error. Although, you can throw a `RunTimeException`, `IllegalArgumentException` and other unchecked exceptions, refer [here](https://www.javatpoint.com/exception-handling-with-method-overriding). – Suleyman May 03 '18 at 21:37
  • I still get an error E/AndroidRuntime: FATAL EXCEPTION: OkHttp Dispatcher Process: com.***.myapplication, PID: 27761 java.lang.RuntimeException: Failed network call – Nikhil May 03 '18 at 21:47
  • You get it when you add `throw RuntimeException` to the method? – Suleyman May 03 '18 at 21:51
  • Yes I tried throw RuntimeException("Failed network call") and added ```throws RuntimeException``` to onFailure I got the above error – Nikhil May 03 '18 at 21:57
  • put `throws new RuntimeException("Failed network call")` – Suleyman May 03 '18 at 22:04
  • Yeah actually tried ```throw new RuntimeException("Failed network call")``` but posted wrong in the above comment. – Nikhil May 03 '18 at 22:18
  • I got confused I think :) Just add inside the method `throw new RuntimeException("Failed network call")` and that's it, or in your method signature add `throws RuntimeException`, one or the other. – Suleyman May 03 '18 at 22:42
  • Tried both separately but it didn't work. – Nikhil May 04 '18 at 13:40
  • So, it goes inside the `onFailure` method, and throws the exception? – Suleyman May 04 '18 at 13:42
  • Goes inside onFailure actually not throwing exception to the calling function instead crashes with E/AndroidRuntime: FATAL EXCEPTION: OkHttp Dispatcher Process: com.***.myapplication, PID: 27761 java.lang.RuntimeException: Failed network call – Nikhil May 04 '18 at 15:39
  • Something I'm missing then, throwing unchecked exceptions should work, checkout [this](https://stackoverflow.com/questions/5875414/why-cant-overriding-methods-throw-exceptions-broader-than-the-overridden-method) post, it should help. – Suleyman May 04 '18 at 15:59

0 Answers0