try catch finally - exception not caught

0 Yaron X · April 18, 2015
When the following code runs, an exception occurs at the setImageResource line. 
When I debug it, the right after that line the debugger jumps to the finally part, and then it goes into some java code in to a method called 
private static class UncaughtHandler implements Thread.UncaughtExceptionHandler 
If I remark the finally section, then the exception is not caught by the catch part?

Why isn't the catch part working?

        try {
            ImageView imageV = (ImageView) findViewById(;

            Log.i(TAG, "before setImageResource");
        } catch (Exception ex) {
        } finally {

Post a Reply


Oldest  Newest  Rating
0 Yaron X · April 19, 2015
Thank you Nathaniel.

I am used from C# to catch just (Exception ex) and that basically catches all exceptions.
A function may result in dozens of possible exceptions, how can one tell which ones to catch?

In any case, this turned out to be not even an exception but a Throwable, something I have not learned yet.
0 Yaron X · April 19, 2015
Thank you Kayler.

setImageResource is definitely the line which throws the error. It is not the Log.e line. 
The app crashed with the code having just setImageResource, without any try and catch. And I did use a debugger to go line by line and it crashes on that line. 
The code got to finally because , as you said so yourself, eventually it always does. That's what finally is all about.
Like I wrote in my reply to myself above, the issue was resolved by adding a catch for Throwable. I am new to Android and Java and I have not learned about throwables yet. But once I added a catch for throwables,the problem was resolved.

try {
} catch (Exception ex) {
}  catch (Throwable ex) {
        Log.e(TAG,"catch (Throwable ex):" + ex.getMessage().toString() + "\n" + ex.getStackTrace());
finally {

BTW, the reason the setImageResource  errored was because the bitmap I used was too big and the error was about memory allocation.
0 Nathaniel Hill · April 19, 2015
You should specify the exception type. For example, IOException instead of Exception
You can find what type of error you need to catch whenever the compiler throws the error
0 Yaron X · April 18, 2015
Fixed by adding a catch for Throwable
  • 1

Java / Android Development


Very popular language used to create desktop applications, website applets, and Android apps.

Bucky Roberts Administrator