Exception的说明
参考:https://docs.oracle.com/javase/8/docs/api/检查异常的定义 The class
Exceptionand any subclasses that are not also subclasses ofRuntimeExceptionare checked exceptions
//继承Exception的检查异常class SimpleException extends Exception{}public class InheritingException {/*throw 抛出异常 可以进行try catch来自己处理或者使用关键字throws让调用者处理throws 如果本方法无法处理得话 在方法签名上进行throws 让调用者处理*/public void f() throws SimpleException{System.out.println("Throwing SimpleException from f()");//检查异常在编译阶段都会提示用户进行处理//如果抛出检查异常的话,1,要么自己显示的处理;2,要么在方法签名处抛出,交给调用者处理throw new SimpleException();}public static void main(String[] args) {InheritingException inheritingException = new InheritingException();try {//调用者进行显示处理inheritingException.f();}catch (SimpleException e){System.err.println("Cautht f()");}}}
检查异常 运行异常<br /> <br /> 综合对比<br />
// FileOutputStream 部分源码如下
public FileOutputStream(File file, boolean append)
throws FileNotFoundException //此处为检查异常的抛出
{
String name = (file != null ? file.getPath() : null);
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkWrite(name);
}
if (name == null) {
throw new NullPointerException();//运行时运行,从Diagrams图可以看出与FileNotFoundException并无继承体系关系
}
if (file.isInvalid()) {
throw new FileNotFoundException("Invalid file path");//抛出检查异常
}
this.fd = new FileDescriptor();
fd.attach(this);
this.append = append;
this.path = name;
open(name, append);
}
