Java异常体系

使用异常为系统保驾护航

image.png

  • 异常应该描述导致当前异常发生的原因
  • 根据异常栈快速定位异常发生的位置
  • 结合异常描述和异常栈解决异常

    C语言的“异常”烦恼

    image.png

  • 上面处理异常的方式带来的问题

    • 代码可读性差
    • 当返回值与异常值相近时,容易混淆
    • 需要调用方分析异常,增加工作量

      Java异常处理流程

      image.png

      Java异常处理机制

  • 正确捕获异常

    • 多个catch字句
    • catch的Error中用或 | 连接多个
    • catch基类Error

image.png

枝繁叶茂的Java异常体系

image.png

异常处理

异常抛出与捕获原则

  • 非必要不使用异常
    • 异常抛出耗费的性能要高于正常判断语句
    • 所以不能一股脑都try起来,问题定位也不好排查
  • 使用描述性消息抛出异常
    • 上下文
    • 关键信息
  • 力所能及的异常一定要处理
  • 异常忽略要有理有据

    TCF流程解析

  • finally中不能有return

image.png

TryWithResource

image.png

image.png

  • 红色流程中catch到的是资源close方法的异常,try中的异常被压缩了
  • 使用getSuppressed 返回附加的被屏蔽的异常

image.png

  1. package com.demo.t31.core.demo;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import java.io.*;
  5. import java.util.ArrayList;
  6. import java.util.List;
  7. import java.util.zip.GZIPOutputStream;
  8. /**
  9. *@Des 抛出异常与捕获处理测试类
  10. *@Date 2020/10/15 15:23
  11. */
  12. @SuppressWarnings("all")
  13. //@Slf4j
  14. public class CatchExceptionTest {
  15. private static final Logger logger = LoggerFactory.getLogger(CatchExceptionTest.class);
  16. public static void main(String[] args) throws IOException {
  17. // A、 捕获单个异常
  18. /* try {
  19. throwException(null);
  20. } catch (Throwable th) {
  21. logger.warn("catched as Throwable:message:{} ",th.getMessage());
  22. th.printStackTrace();
  23. }*/
  24. CatchExceptionTest catchExceptionTest=new CatchExceptionTest();
  25. // 测试foreach源码
  26. catchExceptionTest.testForeach();
  27. //catchExceptionTest.testCatchExceptions();
  28. //catchExceptionTest.testCatchError();
  29. /*String testFinallyReturn=catchExceptionTest.testTryCatchFinally();
  30. logger.info("testFinallyReturn 值为:{}",testFinallyReturn);*/
  31. //catchExceptionTest.testTryWithResource();
  32. //catchExceptionTest.testCustomizeTryRecources();
  33. }
  34. /**
  35. * throwException:抛出单个异常
  36. * @param value
  37. * @return
  38. */
  39. private boolean throwException(String value) {
  40. if (null == value) {
  41. throw new NullPointerException("value is null...");
  42. }
  43. return "testName".equals(value);
  44. }
  45. /**
  46. * throwExceptions:抛出多个异常
  47. * @param value
  48. * @return
  49. */
  50. public boolean throwExceptions(String value) {
  51. if (null == value) {
  52. throw new NullPointerException("value is null...");
  53. }
  54. if ("".equals(value)) {
  55. throw new IllegalArgumentException("value is blank...");
  56. }
  57. if (!"testName".equals(value)) {
  58. throw new RuntimeException("value is not testName...");
  59. }
  60. return true;
  61. }
  62. /**
  63. * 测试 Error、Exception、Throwable抛出及捕获的顺序
  64. */
  65. public void testCatchError() {
  66. try {
  67. throw new Error("An error occurs here");
  68. } catch (Exception e) {
  69. logger.warn("catched as Exception:message:{}, ",e.getMessage());
  70. } catch (Error e) {
  71. logger.error("catched as Error:message:{} ",e.getMessage());
  72. } catch (Throwable t) {
  73. logger.warn("catched as Throwable:message:{} ",t.getMessage());
  74. }
  75. System.out.println("reach the end of the method");
  76. }
  77. /**
  78. * 测试捕获多个异常
  79. */
  80. public void testCatchExceptions(){
  81. // B-1、 捕获多个异常 -- 第一种方法, 多个异常一次捕获多次处理
  82. try {
  83. throwExceptions("");
  84. } catch (NullPointerException ex) {
  85. logger.warn("catched as NullPointerException:message:{} ",ex.getMessage());
  86. ex.printStackTrace();
  87. } catch (IllegalArgumentException ex) {
  88. logger.warn("catched as IllegalArgumentException:message:{} ",ex.getMessage());
  89. ex.printStackTrace();
  90. } catch (RuntimeException ex) {
  91. logger.warn("catched as RuntimeException:message:{} ",ex.getMessage());
  92. ex.printStackTrace();
  93. }
  94. //B-2、 捕获多个异常 -- 第二种方式, 一个 try, 一个 catch
  95. try {
  96. throwExceptions("");
  97. } catch (NullPointerException | IllegalArgumentException ex) {
  98. logger.warn("catched as NullPointerException | IllegalArgumentException :message:{} ",ex.getMessage());
  99. ex.printStackTrace();
  100. }
  101. //B-3、 捕获多个异常 -- 第三种方式, 定义一个范围更大的父类异常对象
  102. try {
  103. throwExceptions("");
  104. } catch (RuntimeException ex) {
  105. logger.warn("catched as RuntimeException :message:{} ",ex.getMessage());
  106. ex.printStackTrace();
  107. }
  108. }
  109. /**
  110. * 测试foreach源码
  111. */
  112. public void testForeach(){
  113. String [] attrs=new String[]{"Joel","LiLei","liuFan","Soloman"};
  114. for (String attr:attrs) {
  115. logger.info("输出的attr是:{}",attr);
  116. }
  117. List<String> listTest = new ArrayList<String>() ;
  118. for (String attr : listTest) {
  119. logger.info("此处因listTest为空集合,从来不执行");
  120. logger.info("此次输出的attr是:{}",attr);
  121. }
  122. List<String> userNames = new ArrayList<String>() {{
  123. add("olis");
  124. add("olis");
  125. add("wang");
  126. add("o");
  127. add(null);
  128. }};
  129. for (String userName : userNames) {
  130. if (userName.equals("olis")) {
  131. userNames.remove(userName);
  132. //break;
  133. logger.info("此次输出的userName是:{}",userName);
  134. }
  135. /*if (null!=userName&&userName.equals("olis")) {
  136. //userNames.remove(userName);
  137. //break;
  138. logger.info("此次输出的userName是:{}",userName);
  139. }*/
  140. }
  141. }
  142. /**
  143. * testTryCatchFinally
  144. * @throws IOException
  145. */
  146. public String testTryCatchFinally() throws IOException {
  147. String t = "" ;
  148. try {
  149. t = "try" ;
  150. return t;
  151. } catch (Exception e) {
  152. // result = "catch";
  153. t = "catch" ;
  154. return t;
  155. } finally {
  156. t = "finally" ;//在finally中修改变量的值并不能改变try{}中已经放入方法返回值中的变量值
  157. //return t; //在finally中使用return 将改变try{}中已经放入方法返回值中的变量值
  158. }
  159. }
  160. /**
  161. * testTryWithResource
  162. */
  163. public void testTryWithResource() throws IOException {
  164. /* //try cacth finally
  165. BufferedInputStream bin = null;
  166. BufferedOutputStream bout = null;
  167. try {
  168. bin = new BufferedInputStream(new FileInputStream(new File("D:\\test\\download urls.txt")));
  169. bout = new BufferedOutputStream(new FileOutputStream(new File("D:\\test\\out.txt")));
  170. int b;
  171. while ((b = bin.read()) != -1) {
  172. bout.write(b);
  173. }
  174. } catch (IOException e) {
  175. logger.error("IOException-catch:{}",e.getMessage());
  176. e.printStackTrace();
  177. } finally {
  178. if (bin != null) {
  179. try {
  180. bin.close();
  181. } catch (IOException e) {
  182. logger.error("IOException-finally-close:{}",e.getMessage());
  183. throw e;
  184. } finally {
  185. if (bout != null) {
  186. try {
  187. bout.close();
  188. }
  189. catch (IOException e) {
  190. throw e;
  191. }
  192. }
  193. }
  194. }
  195. }*/
  196. //try with resource 1 D:\test\download urls.txt
  197. /*try (FileInputStream fin = new FileInputStream(new File("download urls.txt"));
  198. GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(new File("out.txt")))) {
  199. byte[] buffer = new byte[4096];
  200. int read;
  201. while ((read = fin.read(buffer)) != -1) {
  202. out.write(buffer, 0, read);
  203. }
  204. } catch (IOException e) {
  205. logger.error("IOException-catch-try with resource 1:{}",e.getMessage());
  206. e.printStackTrace();
  207. }*/
  208. //try with resource 2
  209. try (FileInputStream fin = new FileInputStream(new File("download urls.txt"));
  210. FileOutputStream fout = new FileOutputStream(new File("out.txt"));
  211. GZIPOutputStream out = new GZIPOutputStream(fout)) {
  212. byte[] buffer = new byte[4096];
  213. int read;
  214. while ((read = fin.read(buffer)) != -1) {
  215. out.write(buffer, 0, read);
  216. }
  217. } catch (IOException e) {
  218. logger.error("IOException-catch-try with resource 2:{}",e.getMessage());
  219. e.printStackTrace();
  220. }
  221. //try with resource JDK9之后
  222. /* final FileInputStream fin = new FileInputStream(new File("download urls.txt"));
  223. FileOutputStream fout = new FileOutputStream(new File("out.txt"));
  224. GZIPOutputStream out = new GZIPOutputStream(fout);
  225. try (fin;fout;out) {
  226. byte[] buffer = new byte[4096];
  227. int read;
  228. while ((read = fin.read(buffer)) != -1) {
  229. out.write(buffer, 0, read);
  230. }
  231. } catch (IOException e) {
  232. logger.error("IOException-catch-try with resource 3:{}",e.getMessage());
  233. e.printStackTrace();
  234. }*/
  235. }
  236. /**
  237. * testCustomizeTryRecources
  238. */
  239. public void testCustomizeTryRecources() {
  240. try (MyAutoCloseTestA a = new MyAutoCloseTestA();
  241. MyAutoCloseTestB b = new MyAutoCloseTestB()) {
  242. a.test();
  243. b.test();
  244. } catch (Exception e) {
  245. logger.error("Main: exception {}",e.getMessage());
  246. //addSuppressed 将一个异常附加到另一个异常身上,从而避免异常屏蔽;getSuppressed方法将返回附加在该异常上已被屏蔽的异常
  247. /* Throwable[] suppressed = e.getSuppressed();
  248. for (int i = 0; i < suppressed.length; i++)
  249. logger.warn("Suppressed Exception:{}",suppressed[i].getMessage());*/
  250. }
  251. }
  252. static class MyAutoCloseTestA implements AutoCloseable {
  253. public void test() throws IOException {
  254. logger.warn("MyAutoCloaseTestA: test()");
  255. throw new IOException("MyAutoCloaseTestA: test() IOException");
  256. }
  257. @Override
  258. public void close() throws Exception {
  259. logger.warn("MyAutoCloseTestA: on close()");
  260. throw new Exception("MyAutoCloaseTestA: close() 执行时发生资源关闭异常");
  261. }
  262. }
  263. static class MyAutoCloseTestB implements AutoCloseable {
  264. public void test() throws IOException {
  265. logger.warn("MyAutoCloaseTestB: test()");
  266. throw new IOException("MyAutoCloaseTestB: test() IOException");
  267. }
  268. @Override
  269. public void close() throws Exception {
  270. logger.warn("MyAutoCloseTestTestB: on close");
  271. throw new Exception("MyAutoCloaseTestB: close() 执行时发生资源关闭异常");
  272. }
  273. }
  274. }

NPE场景及对策

image.png
image.png
image.png
image.png

日志规约

日志时效规约

image.png

日志输出规约

image.png

日志记录规约

image.png

日志扩展规约

image.png

错误码规约

image.png
image.png

异常与日志综合实践

image.png
image.png
image.png
image.png
image.png
image.png
image.png

后续

image.png

产出

exception.zip.delete.java
log.zip.delete.java