33. Java对异常处理的两种方式


  1. 声明异常
    throw: 关键字,用于抛出一个指定的异常对象
    必须写在方法内部必须是Exception或Exception的子类对象
    throws: 用于方法声明上,表示当前方法不处理该异常,提醒调用者处理异常
    方法内部抛出编译器异常
/**
 * 

方式一: 声明异常

* throw, throws * */ public class DeclareException { /** *

使用 throw 关键字抛出运行时异常

* */ private static boolean validate01(String name) { if (null == name) { throw new NullPointerException("name is null..."); } return "qinyi".equals(name); } /** *

编译期异常, 必须处理这个异常, 或者是由 throws 继续抛出给上层调用者处理

* */ private static void validate02(String name) throws EOFException, FileNotFoundException { if (null == name) { throw new EOFException("name is null..."); } if (!"qinyi".equals(name)) { throw new FileNotFoundException("name is not qinyi..."); } } }
  1. 捕获异常
    三个关键字:trycatchfinally
    try:该代码块内编写可能产生异常的代码
    catch:用于进行某种异常的捕获并处理
    finaly: 不管代码出现异常与否,都会对该代码块执行
/**
 * 

方式2: 捕获异常

* try...catch...finally * */ @SuppressWarnings("all") public class CatchException { /** *

validate01 抛出单个异常

* */ private static boolean validate01(String name) { if (null == name) { throw new NullPointerException("name is null..."); } return "qinyi".equals(name); } /** *

validate02 抛出多个异常

* */ private static boolean validate02(String name) { if (null == name) { throw new NullPointerException("name is null..."); } if ("".equals(name)) { throw new IllegalArgumentException("name is blank..."); } if (!"qinyi".equals(name)) { throw new RuntimeException("name is not qinyi..."); } return true; } /** *

打开并关闭 Stream

* */ private static void openAndCloseStream() { Stream pathStream = null; try { pathStream = Files.list(Paths.get("/tmp")); List paths = pathStream.collect(Collectors.toList()); System.out.println(paths.size()); // .... } catch (IOException ex) { ex.printStackTrace(); } finally { if (null != pathStream) { pathStream.close(); } } } public static void main(String[] args) { // 1. 捕获单个异常 try { validate01(null); } catch (Throwable th) { System.out.println(th.getMessage()); th.printStackTrace(); } // 2.1 捕获多个异常 -- 第一种方法, 多一个异常一次捕获多次处理 try { validate02(""); } catch (NullPointerException ex) { System.out.println(ex.getMessage()); ex.printStackTrace(); } catch (IllegalArgumentException ex) { System.out.println(ex.getMessage()); ex.printStackTrace(); } catch (RuntimeException ex) { System.out.println(ex.getMessage()); ex.printStackTrace(); } // 2.2 捕获多个异常 -- 第二种方式, 一个 try, 一个 catch try { validate02(""); } catch (NullPointerException | IllegalArgumentException ex) { System.out.println(ex.getMessage()); ex.printStackTrace(); } // 2.3 捕获多个异常 -- 第三种方式, 定义一个范围更大的父类异常对象 try { validate02(""); } catch (RuntimeException ex) { System.out.println(ex.getMessage()); ex.printStackTrace(); } } }