总结一些Java异常的处理原则java
在finally里关闭资源jvm
public void readFile() { FileInputStream fileInputStream = null; File file = new File("./test.txt"); try { fileInputStream = new FileInputStream(file); int length; byte[] bytes = new byte[1024]; while ((length = fileInputStream.read(bytes)) != -1) { System.out.println(new String(bytes, 0, length)); } } catch (FileNotFoundException e) { logger.error("找不到文件", e); } catch (IOException e) { logger.error("读取文件失败", e); } finally { if (fileInputStream != null) { try { fileInputStream.close(); } catch (IOException e) { logger.error("关闭流失败", e); } } } }
用try-with-resource关闭资源日志
public void readFile2() { File file = new File("./test.txt"); try(FileInputStream fileInputStream = new FileInputStream(file)) { int length; byte[] bytes = new byte[1024]; while ((length = fileInputStream.read(bytes)) != -1) { System.out.println(new String(bytes, 0, length)); } } catch (FileNotFoundException e) { logger.error("找不到文件", e); } catch (IOException e) { logger.error("读取文件失败", e); } }
public void numberFormat() { try { String year = "2018"; System.out.println(Integer.parseInt(year)); } catch (NumberFormatException e) { // 捕获NumberFormatExceptoin而不是Exception logger.error("年份格式化失败", e); // 描述一下异常 } }
// 自定义一个异常 class NotFoundGirlFriendException extends Exception { public NotFoundGirlFriendException(String message) { super(message); } } /** * * @param input * @throws NotFoundGirlFriendException input为空抛出异常 */ public void doSomething(String input) throws NotFoundGirlFriendException { if (input == null) { throw new NotFoundGirlFriendException("出错了"); } }
public int getYear(String year) { int retYear = -1; try { retYear = Integer.parseInt(year); } catch (NumberFormatException e) { logger.error("年份格式化失败", e); } catch (IllegalArgumentException e) { logger.error("非法参数", e); } return retYear; }
public void test6() { try { } catch (Throwable e) { } }
public void test7() { try { } catch (NumberFormatException e) { logger.error("即使你认为不可能走到这个异常,也要记录一下", e); } }
public void foo() { try { new Long("xyz"); } catch (NumberFormatException e) { logger.error("字符串格式化成Long失败", e); throw e; } }
class MyBusinessException extends Exception { public MyBusinessException(String message) { super(message); } public MyBusinessException(String message, Throwable cause) { super(message, cause); } } public void wrapException(String id) throws MyBusinessException { try { System.out.println(Long.parseLong(id)); } catch(NumberFormatException e) { throw new MyBusinessException("ID格式化失败", e); } }