
Java问题中的一个catch代码块捕获多个异常,多个异常具有父子关系 40
一个catch代码块捕获多个异常时,如catch(ClientProtocolException|IOExceptione),其中ClientProtocolExcept...
一个catch代码块捕获多个异常时,如catch(ClientProtocolException | IOException e),其中ClientProtocolException 是IOException 的子类,为何这样写编译不通过呢?
展开
2个回答
展开全部
自 JDK 1.7 开始,Java 允许用一个 catch 来捕获多个异常,但是这多个异常必须是平级关系,不能是父子关系。所谓平级,就是说他们的继承等级是一致的,就是说捕获的多个异常必须有相同数量的父类,例如下面的代码就是用一个 catch 捕获多个异常,其中发生的异常为ArrayIndexOutOfBoundsException(数组索引越界异常):
import java.awt.HeadlessException;
public class ExceptionTest {
public static void main(String[] args) {
int[] arr =new int[2];
try {
System.out.println(arr[2]);
} catch (ArrayIndexOutOfBoundsException | StringIndexOutOfBoundsException | HeadlessException e) {
e.printStackTrace();
}
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询