簡體   English   中英

如何在 Java 6 中捕獲所有已檢查的異常(在單個塊中)?

[英]How to catch all checked exceptions (in a single block) in Java 6?

重要提示:此問題僅與 Java 6(及更低版本)有關。

這里的層次結構顯示 Java Exception分為兩種類型: RuntimeException[not a RuntimeException]

Java 異常層次結構

把它分成像UncheckedExceptionCheckedException這樣的東西不是更好嗎? 例如,下面的語句有不少已檢查的異常:

try {
    transaction.commit();
} catch (SecurityException e) {
} catch (IllegalStateException e) {
} catch (RollbackException e) {
} catch (HeuristicMixedException e) {
} catch (HeuristicRollbackException e) {
} catch (SystemException e) {
}

我只對它是成功還是失敗真正感興趣,所以想將已檢查的異常作為一個組處理,而不是未檢查的異常,因為捕獲意外錯誤不是一個好習慣。 因此,考慮到這一點,也許我可以執行以下操作:

try {
    transaction.commit();
} catch (Exception e) {
    if (e instanceof RuntimeException) {
        // Throw unchecked exception
        throw e;
    }
    // Handle checked exception
    // ...
}

但這似乎非常駭人聽聞。 有沒有更好的辦法?

如果我理解正確,那么您就快到了。 只需捕獲運行時異常。 這將捕獲 RuntimeException 及其層次結構中的所有內容。 然后是 Exception 的失敗,你會被覆蓋:

try {
    transaction.commit();
} catch (RuntimeException e) {
    // Throw unchecked exception
    throw e;
} catch (Exception e) {
    // Handle checked exception
    // ...
}

Java 7允許你這樣的結構:

try {
    transaction.commit();
} catch (SecurityException | IllegalStateException  | RollbackException | HeuristicMixedException  e ) {
   // blablabla
}

UPD:我認為,在早期版本的 Java 中沒有很好和方便的方法來做到這一點。 這就是Java語言開發人員在Java 7引入這種結構的原因。 因此,您可以為Java 6設計自己的方法。

我在另一篇文章中給出了類似的答案,所以是的,它是復制過去的:

我所做的就是擁有一個處理所有異常的靜態方法,並將日志添加到 JOptionPane 以將其顯示給用戶,但您可以將結果寫入FileWriter中的文件中,該文件包裝在BufeeredWriter 對於主要的靜態方法,要捕獲未捕獲的異常,我會這樣做:

SwingUtilities.invokeLater( new Runnable() {
    @Override
    public void run() {
        //Initializations...
    }
});


Thread.setDefaultUncaughtExceptionHandler( 
    new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException( Thread t, Throwable ex ) {
            handleExceptions( ex, true );
        }
    }
);

至於方法:

public static void handleExceptions( Throwable ex, boolean shutDown ) {
    JOptionPane.showMessageDialog( null,
        "A CRITICAL ERROR APPENED!\n",
        "SYSTEM FAIL",
        JOptionPane.ERROR_MESSAGE );

    StringBuilder sb = new StringBuilder(ex.toString());
    for (StackTraceElement ste : ex.getStackTrace()) {
        sb.append("\n\tat ").append(ste);
    }


    while( (ex = ex.getCause()) != null ) {
        sb.append("\n");
        for (StackTraceElement ste : ex.getStackTrace()) {
            sb.append("\n\tat ").append(ste);
        }
    }

    String trace = sb.toString();

    JOptionPane.showMessageDialog( null,
        "PLEASE SEND ME THIS ERROR SO THAT I CAN FIX IT. \n\n" + trace,
        "SYSTEM FAIL",
        JOptionPane.ERROR_MESSAGE);

    if( shutDown ) {
        Runtime.getRuntime().exit( 0 );
    }
}

在你的情況下,你可以像我之前告訴你的那樣寫一個日志,而不是向用戶“尖叫”:

String trace = sb.toString();

File file = new File("mylog.txt");
FileWriter myFileWriter = null;
BufferedWriter myBufferedWriter = null;

try {
    //with FileWriter(File file, boolean append) you can writer to 
    //the end of the file
    myFileWriter = new FileWriter( file, true );
    myBufferedWriter = new BufferedWriter( myFileWriter );

    myBufferedWriter.write( trace );
}
catch ( IOException ex1 ) {
    //Do as you want. Do you want to use recursive to handle 
    //this exception? I don't advise that. Trust me...
}
finally {
    try {
        myBufferedWriter.close();
    }
    catch ( IOException ex1 ) {
        //Idem...
    }

    try {
        myFileWriter.close();
    }
    catch ( IOException ex1 ) {
        //Idem...
    }
}

我希望我有所幫助。

祝你今天過得愉快。 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM