1

I have situation that Activity calls Manager class that calls provider.

Activity -> Manager (method with asyncTask) -> Provider

On provider I throw custom exception

try {
    // here is code that may be exception
} catch (LoadingException e) {
    DataNotAvailableException ex = new DataNotAvailableException();
    ex.initCause(e);
    throw ex;
}

I handle this exception on my Manager class

try {
    //calling provider and catching exception
} catch (DataNotAvailableException e) {
   //TODO rethrow exception to activity
}

But main is problem that I can't throw exception back to the Activity that handles UI. There I want to show message (dialog) to the user, that connection unavailable.

If I try to rethrow exception it gives me error (saying surround try/catch block).

How should I send caught exception back to the activity?

Raghunandan
  • 132,755
  • 26
  • 225
  • 256
Ragaisis
  • 2,700
  • 1
  • 26
  • 41

4 Answers4

1

If you use an AsyncTask instead of a regular thread you could simply structure your logic in a way that if the doInBackground method returned some null/zero value, your onPostExecute would simply display the desired error dialog to your user. If you are unable to use an AsyncTask then you could create a Handler in your UI thread and then when you catch your exception, send a message through the handler to your UI thread, where you could then display your error dialog.

MattC
  • 12,285
  • 10
  • 54
  • 78
0

You can try something like this

try
{
        ...
}
catch (Exception e)
{
     throw new YourOwnException(e);
}
Stormel
  • 143
  • 3
  • 9
0

Throw a new RuntimeException with your caught exception as an argument. RuntimeExceptions aren't checked at compile time.

throw new RuntimeException(e);
Douglas Jones
  • 2,522
  • 1
  • 23
  • 27
  • RuntimeExceptions are really not meant for application-level logic. They are to indicate that something has occurred that the application cannot recover from, usually something in the JVM or the system itself. – MattC Nov 04 '13 at 14:23
  • @MattC I understand they aren't really meant for application logic. I shouldn't have written it that way since I really was meaning the set up runtime exceptions as non-checked exceptions are an option. – Douglas Jones Nov 05 '13 at 23:48
0

You can execute some method on main activity to show message when you caught the exception by two ways.

  1. Make a static method on your mainActivity to show message.
  2. Create an interface to show message and let mainActivity implement it, then pass you activity to the provider as of type YourInterface
Ahmad Dwaik 'Warlock'
  • 5,953
  • 5
  • 34
  • 56