答案很简单:
如果你能处理内部异常,你应该抓住它并做一些合理的事情
如果你不能处理它,你有两个选择:
- 如果异常是特定于实现的,则捕获它并抛出调用者可以接受的异常(通常包装实际异常)
- 如果异常在你的调用者的域中,声明为抛出它并让你的调用者处理它
以下是每种类型的一些示例:
示例 1:处理它:
public void deleteFile(String filename) {
File file = new File(filename);
try {
file.delete();
} catch (FileNotFoundException e) {
// No big deal - it was already deleted
}
}
示例 2:包装它:
public void changePassword(String username, String password) throws UserUpdateException {
try {
// execute SQL to update the password
// but storing the user in a DB is an imlementation choice
// we could use a file on disk or a remote web service to store user info
} catch (SQLException e) {
throw new UserUpdateException(e);
}
}
示例 3:什么都不做:
public void insertIntoDatabase(Record record) throws SQLException {
// execute SQL on the database
// using a DB is implied - let the exception bubble up
}