javaandroidproguardandroid-proguard

ProGuard and UncaughtExceptionHandler


I try to use ProGuard with my own UncaughtExceptionHandler class. Without ProGuard everything works well. But if I enable it the function uncaughtException will never be called.

public class MyBug implements UncaughtExceptionHandler
{
    private UncaughtExceptionHandler defaultUEH;

    public ASBug() {
        alert("init");
        defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
    }

    public void addHandlerToThread(Thread t) {
        alert("set");
        t.setUncaughtExceptionHandler(this);
    }

    @Override
    public void uncaughtException(Thread t, Throwable e)
    {
        alert("catch");
    }


    static void alert(final String message) {

        ***.context().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                AlertDialog.Builder bld = new  AlertDialog.Builder(***.context());
                bld.setMessage(message);
                bld.setNeutralButton("OK", null);
                bld.create().show();
            }
        });
    }
}

proguard-rules.txt

-keepclasseswithmembers public class com.asgardsoft.core.ASBug

Solution

  • To addon to @Viral's answer

    ...ProGuard is probably removing your custom UncaughtExceptionHandler class because it is not being used elsewhere in the code. To prevent that you can add the following line to your proguard-rules.txt file which tells ProGuard to keep the MyBug class and all it's members.

    -keep class com.yourpackage.MyBug { *; }
    

    You can also try adding the following lines to your proguard-rules.txt file to ensure that ProGuard does not optimize or remove any of the methods or fields that are used by your custom UncaughtExceptionHandler:

    -keepattributes Annotation,Signature
    -keepclassmembers class com.yourpackage.MyBug {
    *;
    }
    

    This should prevent ProGuard from removing your custom UncaughtExceptionHandler class and ensure that your uncaughtException() method is called when an unhandled exception occurs.

    For a deeper dive see: https://www.guardsquare.com/en/products/proguard/manual/examples#exceptionhandlers https://www.guardsquare.com/en/products/proguard/manual/troubleshooting#exceptionhandlers