why does the catch block give an error with variable not initialized in Java

后端 未结 7 1137
臣服心动
臣服心动 2021-01-12 00:42

This is the code that I\'ve written.

int num;
try {
    num=100;
    DoSomething();
    System.out.println(num);
} catch(Exception e) {
    DoSomething1();
}         


        
7条回答
  •  粉色の甜心
    2021-01-12 00:53

    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:

    • init var before try-block
    • init var in try-blocks and catch-blocks
    • init var in finally block
    • init var only in try-block, but do not catch exceptions

    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
    

提交回复
热议问题