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

3 java sql exception

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

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

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

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

getCustomer方法还抛出异常和proc.java编译.

确切的错误是

unreported exception java.sql.SQLException; must be caught or declared to be thrown
Run Code Online (Sandbox Code Playgroud)

Out*_*mer 10

通常,如果您的代码需要抛出签名不支持的Exception类型,并且您无法控制接口,则可以捕获并重新抛出接口支持的类型.如果您的接口未声明任何已检查的异常,则始终可以抛出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?
    }
}
Run Code Online (Sandbox Code Playgroud)

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


Dar*_*ron 8

再次阅读错误消息,它为您提供了两个选择.

您必须将异常声明为抛出(您无法执行)或捕获异常.尝试第二选择.