虽然了解一些有关 Java 的异常处理,可是发现本身对 throw 和 throws 两者还不是很清楚,因此想深刻的理解理解。java
系统自动抛出异常、throw 和 throws三种方式。code
一、系统自动抛出异常orm
public class ThrowTest { public static void main(String[] args) { int a = 0; int b = 1; System.out.println(b / a); } }
运行该程序后系统会自动抛出 ArithmeticException 算术异常。对象
Exception in thread "main" java.lang.ArithmeticException: / by zero at com.sywf.study.ThrowTest.main(ThrowTest.java:8)
二、throw
throw 指的是语句抛出异常,后面跟的是对象,如:throw new Exception,通常用于主动抛出某种特定的异常,如:string
public class ThrowTest { public static void main(String[] args) { String string = "abc"; if ("abc".equals(string)) { throw new NumberFormatException(); } else { System.out.println(string); } } }
运行后抛出指定的 NumberFormatException 异常。it
Exception in thread "main" java.lang.NumberFormatException at com.sywf.study.ThrowTest.main(ThrowTest.java:8)
三、throws
throws 用于方法名后,声明方法可能抛出的异常,而后交给调用其方法的程序处理,如:io
public class ThrowTest { public static void test() throws ArithmeticException { int a = 0; int b = 1; System.out.println(b / a); } public static void main(String[] args) { try { test(); } catch (ArithmeticException e) { // TODO: handle exception System.out.println("test() -- 算术异常!"); } } }
程序执行结果:class
test() -- 算术异常!
一、throw 出如今方法体内部,而 throws 出现方法名后。
二、throw 表示抛出了异常,执行 throw 则必定抛出了某种特定异常,而 throws 表示方法执行可能会抛出异常,但方法执行并不必定发生异常。thread