Java异常体系
使用异常为系统保驾护航

- 异常应该描述导致当前异常发生的原因
- 根据异常栈快速定位异常发生的位置
-
C语言的“异常”烦恼

上面处理异常的方式带来的问题
正确捕获异常
- 多个catch字句
- catch的Error中用或 | 连接多个
- catch基类Error
枝繁叶茂的Java异常体系
异常处理
异常抛出与捕获原则
- 非必要不使用异常
- 异常抛出耗费的性能要高于正常判断语句
- 所以不能一股脑都try起来,问题定位也不好排查
- 使用描述性消息抛出异常
- 上下文
- 关键信息
- 力所能及的异常一定要处理
-
TCF流程解析
finally中不能有return
TryWithResource


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

package com.demo.t31.core.demo;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import java.io.*;import java.util.ArrayList;import java.util.List;import java.util.zip.GZIPOutputStream;/***@Des 抛出异常与捕获处理测试类*@Date 2020/10/15 15:23*/@SuppressWarnings("all")//@Slf4jpublic class CatchExceptionTest {private static final Logger logger = LoggerFactory.getLogger(CatchExceptionTest.class);public static void main(String[] args) throws IOException {// A、 捕获单个异常/* try {throwException(null);} catch (Throwable th) {logger.warn("catched as Throwable:message:{} ",th.getMessage());th.printStackTrace();}*/CatchExceptionTest catchExceptionTest=new CatchExceptionTest();// 测试foreach源码catchExceptionTest.testForeach();//catchExceptionTest.testCatchExceptions();//catchExceptionTest.testCatchError();/*String testFinallyReturn=catchExceptionTest.testTryCatchFinally();logger.info("testFinallyReturn 值为:{}",testFinallyReturn);*///catchExceptionTest.testTryWithResource();//catchExceptionTest.testCustomizeTryRecources();}/*** throwException:抛出单个异常* @param value* @return*/private boolean throwException(String value) {if (null == value) {throw new NullPointerException("value is null...");}return "testName".equals(value);}/*** throwExceptions:抛出多个异常* @param value* @return*/public boolean throwExceptions(String value) {if (null == value) {throw new NullPointerException("value is null...");}if ("".equals(value)) {throw new IllegalArgumentException("value is blank...");}if (!"testName".equals(value)) {throw new RuntimeException("value is not testName...");}return true;}/*** 测试 Error、Exception、Throwable抛出及捕获的顺序*/public void testCatchError() {try {throw new Error("An error occurs here");} catch (Exception e) {logger.warn("catched as Exception:message:{}, ",e.getMessage());} catch (Error e) {logger.error("catched as Error:message:{} ",e.getMessage());} catch (Throwable t) {logger.warn("catched as Throwable:message:{} ",t.getMessage());}System.out.println("reach the end of the method");}/*** 测试捕获多个异常*/public void testCatchExceptions(){// B-1、 捕获多个异常 -- 第一种方法, 多个异常一次捕获多次处理try {throwExceptions("");} catch (NullPointerException ex) {logger.warn("catched as NullPointerException:message:{} ",ex.getMessage());ex.printStackTrace();} catch (IllegalArgumentException ex) {logger.warn("catched as IllegalArgumentException:message:{} ",ex.getMessage());ex.printStackTrace();} catch (RuntimeException ex) {logger.warn("catched as RuntimeException:message:{} ",ex.getMessage());ex.printStackTrace();}//B-2、 捕获多个异常 -- 第二种方式, 一个 try, 一个 catchtry {throwExceptions("");} catch (NullPointerException | IllegalArgumentException ex) {logger.warn("catched as NullPointerException | IllegalArgumentException :message:{} ",ex.getMessage());ex.printStackTrace();}//B-3、 捕获多个异常 -- 第三种方式, 定义一个范围更大的父类异常对象try {throwExceptions("");} catch (RuntimeException ex) {logger.warn("catched as RuntimeException :message:{} ",ex.getMessage());ex.printStackTrace();}}/*** 测试foreach源码*/public void testForeach(){String [] attrs=new String[]{"Joel","LiLei","liuFan","Soloman"};for (String attr:attrs) {logger.info("输出的attr是:{}",attr);}List<String> listTest = new ArrayList<String>() ;for (String attr : listTest) {logger.info("此处因listTest为空集合,从来不执行");logger.info("此次输出的attr是:{}",attr);}List<String> userNames = new ArrayList<String>() {{add("olis");add("olis");add("wang");add("o");add(null);}};for (String userName : userNames) {if (userName.equals("olis")) {userNames.remove(userName);//break;logger.info("此次输出的userName是:{}",userName);}/*if (null!=userName&&userName.equals("olis")) {//userNames.remove(userName);//break;logger.info("此次输出的userName是:{}",userName);}*/}}/*** testTryCatchFinally* @throws IOException*/public String testTryCatchFinally() throws IOException {String t = "" ;try {t = "try" ;return t;} catch (Exception e) {// result = "catch";t = "catch" ;return t;} finally {t = "finally" ;//在finally中修改变量的值并不能改变try{}中已经放入方法返回值中的变量值//return t; //在finally中使用return 将改变try{}中已经放入方法返回值中的变量值}}/*** testTryWithResource*/public void testTryWithResource() throws IOException {/* //try cacth finallyBufferedInputStream bin = null;BufferedOutputStream bout = null;try {bin = new BufferedInputStream(new FileInputStream(new File("D:\\test\\download urls.txt")));bout = new BufferedOutputStream(new FileOutputStream(new File("D:\\test\\out.txt")));int b;while ((b = bin.read()) != -1) {bout.write(b);}} catch (IOException e) {logger.error("IOException-catch:{}",e.getMessage());e.printStackTrace();} finally {if (bin != null) {try {bin.close();} catch (IOException e) {logger.error("IOException-finally-close:{}",e.getMessage());throw e;} finally {if (bout != null) {try {bout.close();}catch (IOException e) {throw e;}}}}}*///try with resource 1 D:\test\download urls.txt/*try (FileInputStream fin = new FileInputStream(new File("download urls.txt"));GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(new File("out.txt")))) {byte[] buffer = new byte[4096];int read;while ((read = fin.read(buffer)) != -1) {out.write(buffer, 0, read);}} catch (IOException e) {logger.error("IOException-catch-try with resource 1:{}",e.getMessage());e.printStackTrace();}*///try with resource 2try (FileInputStream fin = new FileInputStream(new File("download urls.txt"));FileOutputStream fout = new FileOutputStream(new File("out.txt"));GZIPOutputStream out = new GZIPOutputStream(fout)) {byte[] buffer = new byte[4096];int read;while ((read = fin.read(buffer)) != -1) {out.write(buffer, 0, read);}} catch (IOException e) {logger.error("IOException-catch-try with resource 2:{}",e.getMessage());e.printStackTrace();}//try with resource JDK9之后/* final FileInputStream fin = new FileInputStream(new File("download urls.txt"));FileOutputStream fout = new FileOutputStream(new File("out.txt"));GZIPOutputStream out = new GZIPOutputStream(fout);try (fin;fout;out) {byte[] buffer = new byte[4096];int read;while ((read = fin.read(buffer)) != -1) {out.write(buffer, 0, read);}} catch (IOException e) {logger.error("IOException-catch-try with resource 3:{}",e.getMessage());e.printStackTrace();}*/}/*** testCustomizeTryRecources*/public void testCustomizeTryRecources() {try (MyAutoCloseTestA a = new MyAutoCloseTestA();MyAutoCloseTestB b = new MyAutoCloseTestB()) {a.test();b.test();} catch (Exception e) {logger.error("Main: exception {}",e.getMessage());//addSuppressed 将一个异常附加到另一个异常身上,从而避免异常屏蔽;getSuppressed方法将返回附加在该异常上已被屏蔽的异常/* Throwable[] suppressed = e.getSuppressed();for (int i = 0; i < suppressed.length; i++)logger.warn("Suppressed Exception:{}",suppressed[i].getMessage());*/}}static class MyAutoCloseTestA implements AutoCloseable {public void test() throws IOException {logger.warn("MyAutoCloaseTestA: test()");throw new IOException("MyAutoCloaseTestA: test() IOException");}@Overridepublic void close() throws Exception {logger.warn("MyAutoCloseTestA: on close()");throw new Exception("MyAutoCloaseTestA: close() 执行时发生资源关闭异常");}}static class MyAutoCloseTestB implements AutoCloseable {public void test() throws IOException {logger.warn("MyAutoCloaseTestB: test()");throw new IOException("MyAutoCloaseTestB: test() IOException");}@Overridepublic void close() throws Exception {logger.warn("MyAutoCloseTestTestB: on close");throw new Exception("MyAutoCloaseTestB: close() 执行时发生资源关闭异常");}}}










