异常包装器类用于封装原始异常,以提供附加上下文、重新抛出异常或捕获特定异常类型。使用场景包括:添加附加上下文,便于理解和调试。重新抛出异常,添加错误消息或堆栈跟踪。捕获特定异常类型,进行特定处理。
何时考虑使用异常包装器类
异常包装器类用于封装原始异常,并提供附加信息或功能。考虑使用异常包装器类的常见情况包括:
实战案例
假设有一个函数 readFile
,该函数负责读取文件。如果文件不存在或无法读取,它将抛出 FileNotFoundException
。为了提供更有用的错误消息,我们可以使用异常包装器类:
public class FileNotFoundExceptionWrapper extends RuntimeException { public FileNotFoundExceptionWrapper(FileNotFoundException e) { super("File not found: " + e.getMessage()); } }
现在,我们可以修改 readFile
函数,使其抛出包装器类异常:
public String readFile(String path) { try { return Files.readString(Paths.get(path)); } catch (FileNotFoundException e) { throw new FileNotFoundExceptionWrapper(e); } }
当文件不存在时,函数将抛出 FileNotFoundExceptionWrapper
异常,该异常包含有关文件路径的附加信息,从而更容易调试。