异常转译:当位于最上层的子系统不需要关心底层的异常细节时,常见的作法时捕获原始异常,把它转换一个新的不同类型的异常,在将新异常抛出。

通常方法捕获底层异常,然后抛高层异常。

 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,处理异常。

 

相关文章:

  • 2021-08-27
  • 2022-12-23
  • 2021-11-05
  • 2022-02-12
  • 2022-12-23
  • 2022-12-23
  • 2021-07-16
  • 2021-11-01
猜你喜欢
  • 2021-08-01
  • 2021-08-08
  • 2021-12-11
  • 2021-07-01
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案