网站开发层次,临汾建设局网站,网站建设需要什么呢,培训中心网站建设一、使用规则 1.throw 用在方法体内#xff0c;而throws 则在方法声明中使用 2. throw 后面是接的一个异常对象#xff0c;只能是一个。而throws后面接的是异常类型#xff0c;可以有多个#xff0c;多个异常之间用英文的逗号进行拼接 3.throw是用在代码逻辑中发生不真确的…一、使用规则 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。