为什么抛出upcasting检查异常

时间:2017-07-31 08:29:48

标签: java exception-handling upcasting checked-exceptions

我注意到某些复杂库中的方法(包括标准JDK)倾向于 DOMDocument::loadHTML(): htmlParseStartTag: misplaced <head> tag in Entity, line: 3 向上转换异常。起初我在Apache POI的源代码中发现了这种现象,稍后再次在public static int smallestInt(int[] args) { return Arrays.stream((Arrays.stream(args) .boxed().toArray( Integer[]::new )) .mapToInt(Integer::intValue).min().getAsInt; } 中再次看到它:

throws

其中java.io.FileWriter的实例化声明此callstack中唯一的已检查异常public FileWriter(String fileName) throws IOException { super(new FileOutputStream(fileName)); } 。但是,声明了FileOutputStream,这是FileNotFoundException的超类。

那么这是什么原因?还是仅仅依赖于程序员的习惯?

1 个答案:

答案 0 :(得分:5)

避免过于频繁地更改API可能是有意义的 今天,一个方法可以在代码中引入IOexception的子类,但明天它可以抛出另一个。

虽然在签名中声明的父异常不是太笼统,并且没有为客户端松散值,但是为异常声明一个基类似乎没问题。
例如,一个不好的用法是声明throw Exception,因为客户端无法理解异常的一般含义并因此处理它。