This is the code that I\'ve written.
int num;
try {
num=100;
DoSomething();
System.out.println(num);
} catch(Exception e) {
DoSomething1();
}
In Java you must init local vars. This is not guaranteed when you've these catch blocks since an exception may be thrown before init the local var in try block and you do not init the var in the catch block. Therefore the local var may not have been initialized after try-catch-finally block.
When you remove the catch block then the var is initialized after try or an exception is thrown and the code after try-block never get executed.
You've following possibilities to fix this:
The local var is not guaranteed to be initialized even when var init is the first thing you do in try-block. For example the executed thread can be stopped with Thread.stop(Throwable)
after entering try-block but before var init. When this happens then the var is not initialized but catch-finally is executed and the code after try-catch-finally as well.
Here's an example to show what I mean:
public static void main(String[] args) throws InterruptedException {
Thread thread = new MyThread();
thread.start();
Thread.sleep(100);
thread.stop(new Exception());
}
private static class MyThread extends Thread {
@Override
public void run() {
int num = -1;
try {
Thread.sleep(600); //just to hit the thread at the right point
num = 100;
System.out.println("blub");
}
catch (Exception e) {
System.out.println("catch");
}
finally {
System.out.println("finally");
}
System.out.println(num);
System.out.println("after all");
}
}
This code prints out:
catch
finally
-1
after all