My “MyException” which shows Toast causes trouble while thrown in threads. How should I reorganize Exception handling?

StackOverflow https://stackoverflow.com/questions/3857676

Question

I have written my own Exception (MyException) and implemented Logging and showing Error Messages in Form of Toasts. Here is the shortform of it...

public class MyException extends Exception {

   public MyException(String msg) {
      Looper.prepare();
       Toast.makeText(Controller.getInstance().getApplicationContext(), msg , Toast.LENGTH_LONG).show();
       //Looper.loop();
       Looper.myLooper().quit();
   }
}

Everything was fine until I now implemented Threads where Exceptions are being thrown and caught.

You probably already have seen, that I played with the Looper Class, but honestly I don't know how to make it work. Is that the right approach? You also can see that I already store a reference of the ApplicationContext in my Controller. Shall I do it with the ActivityContext as well and than make the Toast from this ActivityContext? (But I heard that this is not a good practice in terms of performance)

Update

Is this the way I should go, when an Exception is being caught in a Thread in an Activ ity?

private Runnable exceptionCatchingThread   = new Runnable() {
          @Override
          public void run() {
           try { 
                throw new Exception();
           } catch (Exception e) {
              this.e = e;
              runOnUiThread(handleThreadExceptions); }
           }
    }

private Runnable  handleThreadExceptions  = new Runnable() {
             @Override
              public void run() {
               //Show toast or call the general ExceptionHandler, 
               //which is doing logging and stuff
                Helper.handleException(e);
               }
}
Was it helpful?

Solution

An Exception should be used to notify the caller that a problem occurred. It is the caller's responsibility to do something with that notification, log, toasts, etc. You should not do any of that in the Exception class itself.

You could create a helper method to be called when you catch an exception that does the toasting, etc. If you want to do this from multiple activities, you could create a util function where you pass in the context.

public static void displayExceptionMessage(Context context, String msg) {
 Toast.makeText(context, msg , Toast.LENGTH_LONG).show();
}

and in your activity:

try {
  // something that causes Exception
} catch (MyException e) {
  Helper.displayExceptionMessage(this, e.getMessage());
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top