runOnUiThread 的 Try-Catch

Try-Catch for runOnUiThread

我想通过我的代码捕获一些异常,代码层次如下:

    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) {
    }

但是当运行那样时,它不会捕捉到runOnUiThread内的some code 2some code 4的任何异常,并且是捕捉它们的唯一方法就是在 runOnUiThread 里面有一个 try-catch 块来捕捉它们:

    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) {
    }

那么,runOnUiThread 真的需要这个吗?或者我做错了什么?如果它已经需要这个,是否有某种方法可以全局实现这个而不是每个 runOnUiThread 代码块中的 try-catch

So, is runOnUiThread actually needs this?

是的,当您使用 runOnUiThread 时,您 可以 运行 在不同的处理线程上。这意味着 Runnable 中抛出的每个异常都可能 抛出到与您尝试的线程不同的线程上。

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

自定义 class 扩展 Runnable "Throws" 自定义/任何异常,但这听起来不太舒服。