简体   繁体   中英

Why do I need try-catch with throws in my example?

Could someone please help me to understand why do I need to use (inner) try catch if the method is declared as throwing the same exception.

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(new Runnable() {

            public void run() {
                // TODO Auto-generated method stub
                try {
                    producer();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
        t1.start();
        t1.join();
    }

syntax of producer() is

private static void producer() throws InterruptedException

The answer is that you are defining an anonymous class.

Thread t1 = new Thread(new Runnable() {

        public void run() {            
            try {
                producer(); //This is called in run method!
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });

The declaration of the method that calls producer() is public void run() and this method does not throw the checked exception. Therefore, you have to catch it.

It's logical, because you start new thread, which can live after execution leaves the creating method(if it wasn't main method and if you didn't use Thread.join() ). So you should handle exception independently.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM