1

为了更好地学习 Java,我一直在尝试理解异常处理。我不明白为什么以下代码无法编译。

编译器消息是:

TestExceptionHandling.java:12: error: exception StupidException is never thrown in body of corresponding try statement
                catch (StupidException stupidEx) {
                ^

在该try块中,方法 exTest.doExTest() 被调用。在这个方法中,我捕获了一个 InterruptedException,并在它的catch块中抛出了一个新的 StupidException。

那么为什么编译器说它没有被抛出呢?我错过了什么?任何专家可以帮我看看我的错误吗?

  public class TestExceptionHandling {

    public static void main(String argv[]) {

        String output = "";

        try {
            output = "\nCalling method doExTest:\n";
            exTest.doExTest();
        }

        catch (StupidException stupidEx) {
            System.out.println("\nJust caught a StupidException:\n   " + stupidEx.toString());
        }

        System.out.println(output);
    }   
}   

class exTest {

    static long mainThreadId;

    protected static void doExTest() {  //throws StupidException 

        mainThreadId = Thread.currentThread().getId();
        Thread t = new Thread(){
            public void run(){
                System.out.println("Now in run method, going to waste time counting etc. then interrupt main thread.");
                // Keep the cpu busy for a while, so other thread gets going...
                for (int i = 0; i < Integer.MAX_VALUE; i++) {
                    int iBoxed = (int)new Integer(String.valueOf(i));
                    String s = new String("This is a string" + String.valueOf(iBoxed));
                }   
                // find thread to interrupt...
                Thread[] threads = new Thread[0];
                Thread.enumerate(threads);
                for (Thread h: threads) { 
                    if (h.getId() == mainThreadId) {
                        h.interrupt();
                    }
                }
            }
        };

        t.start();

        try {
            Thread.sleep(5000);
        }

        catch (InterruptedException e){
            System.out.println("\nAn InterruptedException " + e.toString() + " has occurred.   Exiting...");
            throw new StupidException("Got an InterruptedException ", e); // ("Got an InterruptedException.   Mutated to StupidException and throwing from doExTest to caller...", e);
        }   

    }
}

class StupidException extends Exception {

    public StupidException(String message, Throwable t) {
        super(message + " " + t.toString());
    }

    public String toString() {
        return "Stupid Exception:  " + super.toString();
    }
}
4

1 回答 1

2

方法需要显式声明它们抛出异常(运行时异常除外,这有点不同)。尝试将您的doExTest方法声明为

protected static void doExTest() throws StupidException {
    ...
}
于 2015-12-08T22:03:31.630 回答