gpt4 book ai didi

Java——必须抛出异常,但如何抛出?

转载 作者:搜寻专家 更新时间:2023-11-01 03:58:53 25 4
gpt4 key购买 nike

我在 NetBeans 中收到一个错误,说我必须在此方法中抛出 SQLException:

private void displayCustomerInfo(java.awt.event.ActionEvent evt)                                     
{
int custID = Integer.parseInt(customerID.getText());
String info = getCustomerInfo(custID);
results.setText(info);
}

此方法是由 NetBeans 创建的,因此它不允许我编辑签名并引发异常。这就是我创建 getCustomerInfo() 方法的原因。此方法确实会抛出异常,因为它使用一种方法从数据库中检索有关客户的信息。

public String getCustomerInfo(int cid) throws SQLException
{
Customer c = proc.getCustomer(cid);
// get info
return "info";
}

getCustomer 方法也会抛出异常并编译 proc.java。

准确的错误是

unreported exception java.sql.SQLException; must be caught or declared to be thrown

最佳答案

一般来说,如果您的代码需要抛出签名不支持的异常类型,并且您无法控制接口(interface),您可以捕获并作为接口(interface)支持的类型重新抛出。如果您的接口(interface)没有声明任何已检查的异常,您总是可以抛出一个 RuntimeException:

private void displayCustomerInfo(java.awt.event.ActionEven evt)                                     
{
try
{
int custID = Integer.parseInt(customerID.getText());
String info = getCustomerInfo(custID);
results.setText(info);
}
catch (SQLException ex)
{
throw new RuntimeException(ex); // maybe create a new exception type?
}
}

您几乎肯定想要创建一个扩展 RuntimeException 的新异常类型,并让您的客户端代码捕获该异常。否则,您将面临捕获任何 RuntimeException 的风险,包括 NullPointerException、ArrayIndexOutOfBoundsException 等,您的客户端代码可能无法处理这些异常。

关于Java——必须抛出异常,但如何抛出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/677582/

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