调用抛出异常的方法时,是否必须在 Java 中包含 catch 块?

发布于 2024-12-29 15:28:36 字数 768 浏览 3 评论 0原文

我创建一个Android应用程序。并输入一些代码,就像:

public void onCreate(Bundle savedInstanceState) {
...
XmlResourceParser xrp = getResources().getXml(R.xml.OneXml);   <==OneXml is a custom xml file in folder res/xml
...
try {
    ....
    xrp.next();
    .... 
} catch(IOException e) {
        e.printStackTrace();
} catch(XmlPullParserException e) {
        e.printStackTrace();
} 
...

我发现我既不能删除 catch(IOException e) 也不能删除 catch(XmlPullParserException e),当我尝试删除其中之一时,Eclipse在 xrp.next() 处标记错误,并告诉我 未处理的异常类型 IOException未处理的异常类型XmlPullParserException,那么我必须添加两个catch吗?为什么Eclipse要求我强制添加两个catch?没有这两个catch代码就不能编译成功吗?

i create an android application. and typed some codes just like :

public void onCreate(Bundle savedInstanceState) {
...
XmlResourceParser xrp = getResources().getXml(R.xml.OneXml);   <==OneXml is a custom xml file in folder res/xml
...
try {
    ....
    xrp.next();
    .... 
} catch(IOException e) {
        e.printStackTrace();
} catch(XmlPullParserException e) {
        e.printStackTrace();
} 
...

i found that i can neither delete catch(IOException e) nor catch(XmlPullParserException e), when i try to delete one of them, Eclipse marks an error at xrp.next() and tells me that Unhandled exception type IOException or Unhandled exception type XmlPullParserException, so must i add the two catch? why does Eclipse ask me to add two catch compulsively? Can't the code be compiled successfully without the two catch?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

清风无影 2025-01-05 15:28:36

异常处理方式:
我们可以通过两种方式处理“问题语句”(问题语句是任何可以引发异常的语句)。

  • 将语句括在 try-catch 块中。
  • 在方法头中附加一个 throws 子句。

处理重写方法中的异常:
如果您要重写子类中的方法。那么你就不能在其签名中附加额外的 throws 子句。在您的情况下, onCreate 是父类中的一个方法,它在子类中被重写,因此我们不能在其标头中附加 throws 子句。因此,您必须将 onCreate 方法中的任何“问题语句”包含在 try-catch 块中。

示例:
将语句括在 try-catch 块中。

public void myMethod(){
        try{
            // Problem Statement
        }catch(IllegalAccessException e){
            e.printStackTrace();
        }catch(NullPointerException e){
            e.printStackTrace();
        }
    }

在方法头中附加一个 throws 子句。

public void myMethod()
        throws IllegalAccessException, NullPointerException{
            // Problem Statement
    }

重写方法示例:
有效的 throws 子句:重写方法中的 throws 子句如果也在父方法中,则有效。

public class Parent {
    public int method() 
        throws IllegalAccessException,NullPointerException, Exception {
        return 0;
    }
}
public class child extends Parent {
    // throws is part of method because parent method
    // have throws clause
    @Override
    public int method() 
        throws IllegalAccessException, NullPointerException,
            Exception {
            //Problem Statement
        return super.method();
    }
}

无效的 throws 子句:如果重写方法中的 throws 子句不存在于父方法中,则该子句无效。

public class Parent {
    public int method(){
        return 0;
    }
}

public class child extends Parent {
    //**Error:** We can not append throws clause in the method because
    // parent method do not have a throws clause
    @Override
    public int method() 
        throws IllegalAccessException, NullPointerException,
            Exception {
            //Problem Statement
        return super.method();
    }
}

因此,我们必须修改子类的方法并删除 throws 子句,因为在这种特殊情况下父方法不包含 throws 子句。我们必须通过 try-catch 块来处理异常。

public class child extends Parent {
    //**Error:** We can not append throws clause in the method because
    // parent method do not have a throws clause
    @Override
    public int method() {
        try{
            // Problem Statement
        }catch(IllegalAccessException e){
            e.printStackTrace();
        }catch(NullPointerException e){
            e.printStackTrace();
        }
    }
}

Exception Handling ways:
We can handle a 'problem statement' (Problem Statement is any statement which can throw an exception) in two ways.

  • Enclose the statement in try-catch block.
  • Append a throws clause in the method header.

Handling Exception in Overridden Methods:
If you are overriding a method in child class. Then you cannot append extra throws clause in its signature. In your case onCreate is a method in parent class, which is overridden in child class hence we can not append throws clause in it header. So you have to enclose any 'Problem Statements' within onCreate method in try-catch blocks.

Examples:
Enclose the statement in try-catch block.

public void myMethod(){
        try{
            // Problem Statement
        }catch(IllegalAccessException e){
            e.printStackTrace();
        }catch(NullPointerException e){
            e.printStackTrace();
        }
    }

Append a throws clause in the method header.

public void myMethod()
        throws IllegalAccessException, NullPointerException{
            // Problem Statement
    }

Examples Overridden Methods:
Valid throws clause: A throws clause in overridden method is valid if it is also in parent'smethod.

public class Parent {
    public int method() 
        throws IllegalAccessException,NullPointerException, Exception {
        return 0;
    }
}
public class child extends Parent {
    // throws is part of method because parent method
    // have throws clause
    @Override
    public int method() 
        throws IllegalAccessException, NullPointerException,
            Exception {
            //Problem Statement
        return super.method();
    }
}

Invalid throws clause: A throws clause in overridden method is invalid if it is not present in parent's method.

public class Parent {
    public int method(){
        return 0;
    }
}

public class child extends Parent {
    //**Error:** We can not append throws clause in the method because
    // parent method do not have a throws clause
    @Override
    public int method() 
        throws IllegalAccessException, NullPointerException,
            Exception {
            //Problem Statement
        return super.method();
    }
}

So we have to modify our child class's method and remove throws clause as parent method do not contain throws clause in this particular situation. We have to handle exception through try-catch block.

public class child extends Parent {
    //**Error:** We can not append throws clause in the method because
    // parent method do not have a throws clause
    @Override
    public int method() {
        try{
            // Problem Statement
        }catch(IllegalAccessException e){
            e.printStackTrace();
        }catch(NullPointerException e){
            e.printStackTrace();
        }
    }
}
和我恋爱吧 2025-01-05 15:28:36

在 Java 中,您必须捕获异常或声明调用该方法可能会导致异常的事实,如下所示:

public void onSomethingOtherThanCreate(Bundle savedInstanceState) 
  throws IOException, XmlPullParserException
{
   // your code without any try/catch
} 

(ErrorRuntimeException 异常可能随时发生不需要以这种方式声明。)

In Java you have to either catch exceptions or declare the fact that calling the method might result in an exception, like so:

public void onSomethingOtherThanCreate(Bundle savedInstanceState) 
  throws IOException, XmlPullParserException
{
   // your code without any try/catch
} 

(Error and RuntimeException exceptions which can happen any time do not need to be declared in this way.)

双马尾 2025-01-05 15:28:36

这不是 Eclipse,而是 Java!

在方法中,引发异常的代码必须驻留在 try-catch 块内,除非在方法声明本身中使用了针对未处理异常的 throws 子句。

It's not Eclipse, it's Java!

In a method, code which throws exceptions must reside inside a try-catch block unless the throws clause for the unhanded exception is used in the method declaration itself.

陌伤浅笑 2025-01-05 15:28:36

这就是检查异常的含义:您必须捕获它们,或者声明它们抛出。

onCreate 正在被重写,并且必须遵守原始方法的声明,因此要么捕获它们,要么在捕获它们的另一个方法中完成这部分工作,是您唯一的选择。

请参阅 JLS 11 异常,特别是 JLS 11.2.3 异常检查,了解详细信息。

That's what checked exceptions mean: you must either catch them, or declare them thrown.

onCreate is being overridden and must adhere to the original method's declaration, so either catching them, or doing that part of the work in another method that catches them, is your only option.

See JLS 11 Exceptions, specifically JLS 11.2.3 Exception Checking, for details.

入画浅相思 2025-01-05 15:28:36

如果您抱怨必须输入两个 catch 子句,则可以在单个子句中捕获所有它们,

catch (Exception e) {
      // dostuff here
   }

但是,除非您计划做的只是打印堆栈跟踪或记录异常,这种做法是不受欢迎的。从长远来看,这将使代码更难调试和维护。

Java 7 允许您在单个异常中捕获多个异常子句,但 Android 尚不支持 Java 7。

If your complaint is that you have to type two catch clauses, it is possible to catch them all in a single clause,

catch (Exception e) {
      // dostuff here
   }

However, unless all you plan to do is print a stack trace or log the exception, this practice is frowned upon. In the long run it will make the code harder to debug and maintain.

Java 7 allows you to catch multiple exceptions in a single clause, but Android doesn't yet support Java 7.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文