一、throw关键字 点击此处返回总目录 二、throws关键字 三、自己写方法抛出异常 四、举例 一、throw关键字 关键字throw,用于在方法的内部抛出异常。 throw抛出的是异常的对象。throw后面,必须写 new 对象(Exception或Exception的子类对象)。 二、throws关键字 throws关键字标明此方法可能会出现哪些异常,请调用者处理。 throws关键字是方法中声明异常的关键字。用于在方法的声明上,标明此方法可能会出现哪些异常,请调用者处理。 三、自己写方法抛出异常 我们可以自己编写方法往外抛异常。 规则和原则如下: 1. 当方法内可能抛出编译异常时(可以是我们使用throw手动抛出,也可以是JVM抛出),必须要写throws声明。【例1】 2. 如果方法内可能抛出编译异常,但是声明上没有写throws,则程序报错。【例2】【例3】 3. 如果方法内抛出了运行异常(可以是我们使用throw手动抛出,也可以是JVM抛出),不需要写throws声明。(在API文档中,带有throws的方法,抛出的异常都是编译异常。所以自己写方法的时候也尽量满足:编译异常写throws,运行异常不写throws)。 例1:
package cn.itcast.demo02; public class Test { public static void main(String[] args) { } //fun():返回最后一个元素*2 public static int fun(int[] arr) throws Exception{ //throws标明可能抛出哪些异常 if(arr == null){ throw new Exception("传入的数组不存在"); //throw往外抛异常,抛给调用者 } if(arr.length == 0){ throw new Exception("传入的数组没有元素"); } int i = arr[arr.length -1]; return i*2; } } |
例2:
package cn.itcast.demo05; import java.text.SimpleDateFormat; import java.util.Date; public class Test { public static void main(String[] args) { fun(); } public static void fun(){ //程序可能抛出编译异常,没有写throws,报错。 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date date = sdf.parse("2088-8-8"); System.out.println(date); } } |
运行结果: Exception in thread "main" java.lang.Error: Unresolved compilation problem: Unhandled exception type ParseException at cn.itcast.demo05.Test.fun(Test.java:13) at cn.itcast.demo05.Test.main(Test.java:9) 例3:用throw抛出了编译异常,但是没有使用throws,则程序报错。
package cn.itcast.demo03; public class Test { public static void main(String[] args) { int[] arr = null; fun(arr); } public static int fun(int[] arr) { //没有写throws关键字,程序报错。 if(arr == null){ throw new Exception("数组不存在"); } return arr[3]; } } |
运行结果: Exception in thread "main" java.lang.Error: Unresolved compilation problem: Unhandled exception type Exception at cn.itcast.demo03.Test.fun(Test.java:11) at cn.itcast.demo03.Test.main(Test.java:6) 四、举例 编写一个方法,输入圆的半径r,输出圆的面积。 分析:当输入的是负数的时候,是异常。虽然能计算Pai*r*r,但是参数违反了真实情况,后面没有什么意义了,应该停止程序,不要计算了。所以应该定义一个运行时异常。这个地方抛出编译异常不合适,因为就不能让调用者处理。 调用者调用我们定义的函数fun()的时候,并不知道里面会抛出运行时异常,也就不会做任何异常方面的处理。当调用了fun(-3)时,程序停了,报了"半径为负"的错误,才发现:"奥,原来是我传了个-3,回去改改"。
package cn.itcast.demo05; public class Test { public static void main(String[] args) { double area = fun(-3); System.out.println(area); } public static double fun(double r){ if(r<0){ throw new RuntimeException("半径为负"); } return r*r*Math.PI; } } |
运行结果: Exception in thread "main" java.lang.RuntimeException: 半径为负 at cn.itcast.demo05.Test.fun(Test.java:14) at cn.itcast.demo05.Test.main(Test.java:9) |