[英]How to catch all checked exceptions (in a single block) in Java 6?
IMPORTANT: This question only relates to Java 6 (and below).重要提示:此问题仅与 Java 6(及更低版本)有关。
The hierarchy here shows Java Exception
s are divided into two types: RuntimeException
and [not a RuntimeException] : 这里的层次结构显示 Java
Exception
分为两种类型: RuntimeException
和[not a RuntimeException] :
Would it not have been better to divide into something like UncheckedException
and CheckedException
instead?把它分成像
UncheckedException
和CheckedException
这样的东西不是更好吗? For example, the following statement has quite a few checked exceptions:例如,下面的语句有不少已检查的异常:
try {
transaction.commit();
} catch (SecurityException e) {
} catch (IllegalStateException e) {
} catch (RollbackException e) {
} catch (HeuristicMixedException e) {
} catch (HeuristicRollbackException e) {
} catch (SystemException e) {
}
Am only really interested in whether it succeeds or fails so would like to deal with the checked exceptions as a group but not the unchecked exceptions as it's not good practice to catch an unexpected error.我只对它是成功还是失败真正感兴趣,所以想将已检查的异常作为一个组处理,而不是未检查的异常,因为捕获意外错误不是一个好习惯。 So with this in mind, maybe I could do something like:
因此,考虑到这一点,也许我可以执行以下操作:
try {
transaction.commit();
} catch (Exception e) {
if (e instanceof RuntimeException) {
// Throw unchecked exception
throw e;
}
// Handle checked exception
// ...
}
But this seems horribly hacky.但这似乎非常骇人听闻。 Is there a better way?
有没有更好的办法?
If I understood correctly, then you are almost there.如果我理解正确,那么您就快到了。 Just catch RuntimeException.
只需捕获运行时异常。 That will catch RuntimeException and everything under it in the hierarchy.
这将捕获 RuntimeException 及其层次结构中的所有内容。 Then a fallthrough for Exception, and you're covered:
然后是 Exception 的失败,你会被覆盖:
try { transaction.commit(); } catch (RuntimeException e) { // Throw unchecked exception throw e; } catch (Exception e) { // Handle checked exception // ... }
Java 7
allows you such constructions: Java 7
允许你这样的结构:
try {
transaction.commit();
} catch (SecurityException | IllegalStateException | RollbackException | HeuristicMixedException e ) {
// blablabla
}
UPD: I think, that there isn't nice and convenient way for doing it in earlier versions of Java. UPD:我认为,在早期版本的 Java 中没有很好和方便的方法来做到这一点。 That is why developers of
Java
language introduced such construction in Java 7
.这就是
Java
语言开发人员在Java 7
引入这种结构的原因。 So, you could devise your own approaches for Java 6
.因此,您可以为
Java 6
设计自己的方法。
I gave a similar answer in another post, so yes, it is copy past:我在另一篇文章中给出了类似的答案,所以是的,它是复制过去的:
Something that I do is to have a static method that handles all exceptions and I add the log to a JOptionPane to show it to the user, but you could write the result to a file in FileWriter
wraped in a BufeeredWriter
.我所做的就是拥有一个处理所有异常的静态方法,并将日志添加到 JOptionPane 以将其显示给用户,但您可以将结果写入
FileWriter
中的文件中,该文件包装在BufeeredWriter
。 For the main static method, to catch the Uncaught Exceptions I do:对于主要的静态方法,要捕获未捕获的异常,我会这样做:
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 );
}
}
);
And as for the method:至于方法:
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 );
}
}
In you case, instead of "screaming" to the user, you could write a log like I told you before:在你的情况下,你可以像我之前告诉你的那样写一个日志,而不是向用户“尖叫”:
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...
}
}
I hope I have helped.我希望我有所帮助。
Have a nice day.祝你今天过得愉快。 :)
:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.