Java之throw 和 throws 的区别
开发工具与关键技术:MyEclipse 10,java
作者:刘东标
撰写时间:2019-06-09
1、声明异常(throws)
在可能出现异常的方法上声明抛出可能出现异常的类型:
声明的时候尽可能声明具体的异常,方便更好的处理.
当前方法不知道如何处理这种异常,可将该异常交给上一级调用者来处理(非 RuntimeException 类型的异常)。
方法一旦使用 throws 声明抛出方法内可能出现的异常类型, 该方法就可以不再过问该 异常了;
一个方法调用另一个使用 throws 声明抛出的方法,自己要么 try…catch , 要么也 throws;
格式:
public 返回值类型 方法名(参数列表…)
throws 异常类 A,异常类 B…{
}
2、throw
自行抛出一个异常对象,抛出异常类的对象;
若throw 抛出的是 Runtime 异常:
程序可以显示使用 try…catch 来捕获并处理,也可以不管,直接交给方法调用者处理;
若throw 抛出 Checked 异常:
要么放在 try里自己处理,要么放在一个 throws 声明的方法里面,交给调用者处理。
Eg:
public static void main(String[] args) {
try {
fn1(1);
} catch (Exception e) {
e.printStackTrace();
}
fn2(2);
}
public static void fn1(int a) throws Exception {
if (a > 0) {
throw new Exception("fn1 --a 值不合法");
}
}
public static void fn2(int a) {
if (a > 0) {
thrownewRuntimeException("a 值不合法");
}
}
``
throws &throw
throws 用于在方法上声明该方法不需要处理的异常类型。
throw 用于抛出具体异常类的对象。
throws 与 throw的区别:
thorws 用在方法上,后面跟异常类名,可以是多个异常类。
throw 用在方法内,后面跟异常对象,只能是一个。