gpt4 book ai didi

java - 在方法之外抛出异常 - Java

转载 作者:行者123 更新时间:2023-12-01 19:53:17 25 4
gpt4 key购买 nike

我是 Java 初学者。

我将一个方法声明为 public void method() throws Exception,但每当我尝试使用 method(); 在同一类的另一个区域中调用该方法时;,我收到错误:

Error: unreported exception java.lang.Exception; must be caught or declared to be thrown

如何使用该方法而不出现此错误?

最佳答案

在调用 method() 的另一个方法中,您必须以某种方式处理 method() 引发的异常。在某些时候,它要么需要被捕获,要么需要一直声明到启动整个程序的 main() 方法。因此,要么捕获异常:

try {
method();
} catch (Exception e) {
// Do what you want to do whenever method() fails
}

或在您的其他方法中声明它:

public void otherMethod() throws Exception {
method();
}

关于java - 在方法之外抛出异常 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33967233/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com