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