当基类需要捕获异常时,在派生类构造函数中使用超 [英] Using Super in a Derived Class Constructor When Base Class Requires Exceptions to be Caught
本文介绍了当基类需要捕获异常时,在派生类构造函数中使用超的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在Java中将类B派生为新的类C.基类构造函数要求必须抛出或捕获未报告的异常。但是如果我尝试把super(..)放在一个try / catch,然后我被告知调用super必须是构造函数中的第一个语句。
公共类C扩展B
{
//后续尝试在构造函数生成错误Undeclared exception E;必须被捕获或声明
//被抛出
public C(String s)
{
super(s);
}
//但下面的例子也失败,因为调用super必须是构造函数中的第一个语句
public C(String s)
{
try
{
super(s);
}
catch(Exception e)
{
}
}
}
非常感谢,
Chris解决方案您可以随时使用throws子句声明构造函数签名中的
异常
。public C(String s)throws WhatEverException
{
I'm trying to derive a class B to a new class C in Java. The base class constructor requires that unreported exceptions must be thrown or caught. But if I try to put super(..) inside a try/catch then I'm told that the call to super must be the first statement in the constructor. Does anyone know a way around this?
public class C extends B { //Following attempt at a constructor generates the error "Undeclared exception E; must be caught or declared //to be thrown public C(String s) { super(s); } //But the below also fails because "Call to super must be the first statement in constructor" public C(String s) { try { super(s); } catch( Exception e) { } } }
Many thanks, Chris
解决方案You can always declare the
Exception
in constructor signature using throws clause.public C(String s) throws WhatEverException {
这篇关于当基类需要捕获异常时,在派生类构造函数中使用超的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文