androidexceptiontry-catchandroid-runonuithread

Try-Catch for runOnUiThread


I want to catch some exception through my code, the code hierarchy is like the following:

    try {
        // some code 1
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // some code 2
            }
        });

        // some code 3
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // some code 4
            }
        });
    } catch (Exception ex) {
    }

But when running like that, it doesn't catch any exception of some code 2 and some code 4 which are inside runOnUiThread, and the only way to catch them is to have a try-catch block inside runOnUiThread to catch them:

    try {
        // some code 1
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    // some code 2
                } catch (Exception e) {
                }
            }
        });

        // some code 3
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    // some code 4
                } catch (Exception e) {
                }
            }
        });
    } catch (Exception ex) {
    }

So, is runOnUiThread actually needs this? or I'm doing something wrong? and if it's already needs this, is there is some way to globally achieve this rather than a try-catch inside each runOnUiThread code block?


Solution

  • So, is runOnUiThread actually needs this?

    yes, when you use the runOnUiThread you may run on a different processing thread. That means that every exception thrown inside the Runnable may be thrown on a different thread than the one where you put your try.

    is there is some way to globally achieve this rather than a try-catch inside each runOnUiThread code block?

    Having a custom class extending Runnable that "Throws" a custom / any Exception, but that doesn't sound really comfortable to do.