
1.捕获特定异常 始终首先捕捉最具体的异常。这有助于识别确切的问题并妥善处理。
try {
// code that may throw an exception
} catch (filenotfoundexception e) {
// handle filenotfoundexception
} catch (ioexception e) {
// handle other ioexceptions
}
2。避免空的 catch 块 空的 catch 块会隐藏错误,使调试变得困难。始终记录异常或采取一些操作。
try {
// code that may throw an exception
} catch (ioexception e) {
e.printstacktrace(); // log the exception
}
3。使用 final 块进行清理 finally 无论是否抛出异常,块都用于执行重要代码,例如关闭资源。
bufferedreader reader = null;
try {
reader = new bufferedreader(new filereader("file.txt"));
// read file
} catch (ioexception e) {
e.printstacktrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (ioexception e) {
e.printstacktrace();
}
}
}
4.不要抓住可抛出的东西 避免捕获 throwable,因为它包含了不应该捕获的错误,比如 outofmemoryerror。
try {
// code that may throw an exception
} catch (exception e) {
e.printstacktrace(); // catch only exceptions
}
5.正确记录异常 使用 log4j 或 slf4j 等待日志框架记录异常,而不是使用 system.out.println。
private static final logger logger = loggerfactory.getlogger(myclass.class);
try {
// code that may throw an exception
} catch (ioexception e) {
logger.error("an error occurred", e);
}
6.必要时重新抛出异常 有时,最好在记录异常或执行某些操作后再次抛出异常。
try {
// code that may throw an exception
} catch (ioexception e) {
logger.error("an error occurred", e);
throw e; // rethrow the exception
}
7。使用 multi-catch 块 在 java 7 在更高的版本中,你可以在单个版本中 catch 多个异常被捕获在块中。
try {
// code that may throw an exception
} catch (ioexception | sqlexception e) {
e.printstacktrace(); // handle both ioexception and sqlexception
}
8.避免过度使用控制流异常 常规控制流不适用于异常。它们适用于特殊条件。
// Avoid this
try {
int value = Integer.parseInt("abc");
} catch (NumberFormatException e) {
// Handle exception
}
// Prefer this
if (isNumeric("abc")) {
int value = Integer.parseInt("abc");
}
以上就是使用 try-catch 更多关于图灵教育的其他相关文章,请关注块处理异常的最佳实践细节!