Effective java 系列之异常转译
异常转译:当位于最上层的子系统不需要关心底层的异常细节时,常见的作法时捕获原始异常,把它转换一个新的不同类型的异常,在将新异常抛出。
通常方法捕获底层异常,然后抛高层异常。
public static long write2File(String dataStr, String filePath) { long fileSize = 0L; try ( RandomAccessFile raf = new RandomAccessFile(createFileAbsolute(filePath), "rw"); FileChannel fchannel = raf.getChannel() ) { ByteBuffer buf = ByteBuffer.allocate(1024); buf.clear(); buf.put(dataStr.getBytes()); buf.flip(); while (buf.hasRemaining()) { fchannel.write(buf); } fileSize = fchannel.size(); } catch (FileNotFoundException e) { //e.printStackTrace(); logger.error("",e); throw new RuntimeException("File not found"); } catch (IOException e) { //e.printStackTrace(); logger.error("",e); throw new RuntimeException("File not found"); } return fileSize; }
然后调用方法去捕获RunTimeException,处理异常。