0

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?

Muhammed Refaat
  • 8,914
  • 14
  • 83
  • 118
  • First of all, why do you need runOnUiThread() at all? What exceptions are you catching? – Egor Apr 09 '15 at 15:34
  • 1
    http://stackoverflow.com/a/6548203/2197087 See this answer – Ivan Skoric Apr 09 '15 at 15:35
  • @Egor It's an app which UI changes according to regular server responses, and these responses require a lot of parsing and processing at first to extract the info needed, So, I made all the parsing and processing in a background thread and ran the UI thread for the UI changes only. – Muhammed Refaat Apr 10 '15 at 12:40
  • @IvanSkoric I know about catching the uncaught exceptions and I'm using it in my app but in fact I don't want to make the app reloads from begging (this is the action I'm using when catch uncaught exception) every time I receive an Exception from this class in specific. – Muhammed Refaat Apr 10 '15 at 12:45

1 Answers1

3

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.

NirIzr
  • 3,131
  • 2
  • 30
  • 49
CptEric
  • 897
  • 9
  • 23