如何在Java中捕获所有已检查的异常(在单个块中)?

时间:2013-02-08 11:10:37

标签: java exception try-catch runtimeexception checked-exceptions

编辑:此问题仅与Java 1.6(及以下)有关。抱歉在原帖中没有说清楚。

层次结构here显示Java Exception分为两种类型:RuntimeException而不是RuntimeException

Java exceptions hierarchy

我可能遗漏了一些东西,但最好是分成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
    // ...
}

但这看起来非常糟糕。还有更好的方法吗?

3 个答案:

答案 0 :(得分:6)

如果我理解正确,那么你几乎就在那里。抓住RuntimeException。这将捕获RuntimeException及其下层的所有内容。然后是Exception的一个漏洞,你就被覆盖了:

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

答案 1 :(得分:5)

Java 7允许你进行这样的构造:

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

UPD:我认为,在早期版本的Java中没有好的方便的方法。这就是为什么Java语言的开发人员在Java 7中引入了这种结构的原因。因此,您可以为Java 6设计自己的方法。

答案 2 :(得分:0)

我在另一篇文章中给出了类似的答案,所以是的,它是复制过去的:

我所做的是拥有一个处理所有异常的静态方法,并将日志添加到JOptionPane以向用户显示,但是您可以将结果写入FileWriter中的文件中。 BufeeredWriter。 对于main静态方法,要捕获我所做的Uncaught Exceptions:

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...
    }
}

我希望我有所帮助。

祝你有个愉快的一天。 :)

相关问题