一、使用规则
1.
throw
用
在方法体内,而throws
则在方法声明中使用
2. throw 后面是接的一个异常对象,只能是一个。而throws后面接的是异常类型,可以有多个,多个异常之间用英文的逗号进行拼接
3.throw是用在代码逻辑中发生不真确的情况时,手动抛出异常,结束一整个方法的代码逻辑,执行了throw的语句,一定会抛出异常。而throws是用来声明当前方法可能会出现某种异常,如果出现了异常,由调用者来处理,声明了异常,但当前方法不一定会发生异常。
二、举例
其实无论是throw还是throws 都是由java的异常机制来处理的
throw
public class Student {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
if ("123".equals(name)){
throw new ServerDisposeException("0","非法的姓名!");
}
this.name = name;
}
}
public class ServerDisposeException extends RuntimeException {
private static final long serialVersionUID = 1L;
private String errCode;
private String errMsg;
public ServerDisposeException() {
}
public ServerDisposeException(String message, Throwable cause) {
super(message, cause);
}
public ServerDisposeException(String message) {
super(message);
}
public ServerDisposeException(Throwable cause) {
super(cause);
}
public ServerDisposeException(String errCode, String errMsg) {
super(errCode + ":" + errMsg);
this.errCode = errCode;
this.errMsg = errMsg;
}
public String getErrCode() {
return this.errCode;
}
public String getErrMsg() {
return this.errMsg;
}
}
如上,ServerDisposeException是可自己定义好的异常类。
当我们校验到姓名不合法时,可以通过throw手动抛出我们已经建好了的异常类进行抛出,用来终结这个方法
throws
public void writeFile(String path) throws IOException {
FileInputStream fileInputStream = new FileInputStream(path);
String resultUrl = "D:/img/21339/abc.jpg";
//图片存入指定目录
FileOutputStream fo = new FileOutputStream(resultUrl);
byte[] flas = new byte[1000];
int x = 0;
while ((x = fileInputStream.read(flas)) != -1) {
//从指定的字节数组开始到当前输出流关闭写入len字节
fo.write(flas, 0, x);
fo.flush();
}
}
1.如上,我们需要将一个文件写入到 D:/img/21339/abc.jpg下。当我们去获取文件输入流时,FileInputStream的构造方法是throws FileNotFoundException ,也就是说他声明了可能会存在这个 FileNotFoundException(文件无法找到)的异常。
2.但是我们调用FileInputStream类的构造方法时,当前代码块自己也不处理这个异常,所以我们选择继续往外声明,让调用我们这个writeFile(String path)方法的那个代码自己去处理。
这里可能有人会有疑问了,FileInputStream的构造方法是throws FileNotFoundException,而为什么我这里是throws IOException?
这里是这样的,我们的代码块里面是还调用了FileInputStream的read方法,而这个read方法源码里面是throws IOException。
然后FileNotFoundException类是extends IOException的,因为IOException是FileNotFoundException的父类。所以我们这里若单纯的throws FileNotFoundException是不行的,所以需要throws IOException。