异常、try-catch 与 try-with-resources
异常表示正常返回值无法表达的失败或异常状态。不要捕获后静默忽略;应处理、转换或让调用方知道失败。
try {
int value = Integer.parseInt(text);
return value;
} catch (NumberFormatException error) {
throw new IllegalArgumentException("必须是整数:" + text, error);
}
catch 应尽量具体。捕获 Exception 会掩盖编程错误和本应暴露的问题。
自动关闭资源
实现 AutoCloseable 的资源应使用 try-with-resources,代码块结束时会自动调用 close():
文件、网络连接和数据库连接都属于应及时关闭的资源。不要只依赖垃圾回收器来释放它们。