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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/677582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 13:21:24  来源:igfitidea点击:

Java -- Exception must be thrown, but how?

javasqlexception

提问by Darron

I am getting an error in NetBeans saying I must throw an SQLException in this method:

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

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

This method is created by NetBeans so it is not allowing me to edit the signature and throw the exception. This is why I created the getCustomerInfo()method. This method does throw the exception, because it uses a method to retrieve information from a database about a customer.

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

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

The getCustomermethod also throws the exception and proc.java compiles.

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

The exact error is

确切的错误是

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

回答by Outlaw Programmer

In general, if your code needs to throw a type of Exception that the signature doesn't support, and you have no control over the interface, you can catch and rethrow as a type the interface does support. If your interface doesn't declare ANY checked exceptions, you can always throw a RuntimeException:

通常,如果您的代码需要抛出签名不支持的异常类型,并且您无法控制接口,则可以捕获并重新抛出接口支持的类型。如果你的接口没有声明任何已检查的异常,你总是可以抛出一个 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?
    }
}

You almost definitely want to create a new Exception type that extends RuntimeException, and have your client code catch that exception. Otherwise, you run the risk of catching ANY RuntimeException, including NullPointerException, ArrayIndexOutOfBoundsException, etc., which your client code probably can't handle.

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

回答by Darron

Read the error message again, it gives you two choices.

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

You must either declare the exception as thrown (which you cannot do) or catch the exception. Try the 2nd choice.

您必须将异常声明为抛出(您不能这样做)或捕获异常。尝试第二个选择。

回答by Art Doler

You need to put a try/catch block around your call to getCustomerInfo(), like so:

您需要在对 的调用周围放置一个 try/catch 块getCustomerInfo(),如下所示:

private void displayCustomerInfo(java.awt.event.ActionEvent evt)                                     
{                                         
    int custID = Integer.parseInt(customerID.getText());
    try {
        String info = getCustomerInfo(custID);
    } catch (SQLException sqle) {
        // Do something with the exception
    }

    results.setText(info);
}

A couple good options for handling the exception might be: logging the exception and the details used to get it, or using it as a signal to retry the connection request. Alternatively, as Outlaw Programmer shows, you could re-throw the Exception as a RuntimeException of some kind, which removes the requirement of checking.

处理异常的几个不错的选择可能是:记录异常和用于获取它的详细信息,或者将其用作重试连接请求的信号。或者,正如 Outlaw Programmer 所示,您可以将 Exception 作为某种 RuntimeException 重新抛出,这消除了检查的要求。

回答by Joe Phillips

It does not say you must throw it. It says you can catch it. So use a try/catch block and handle it.

它并没有说你必须扔掉它。它说你可以抓住它。所以使用 try/catch 块并处理它。

try {
    ...
}
catch (SQLException e) {
    System.out.println("Exception happened! Abort! Abort!");
    e.printMessage(); //Not sure if this is the correct method name
}

回答by EAKAE

NetBeans generated components have un-modifiable code, and I'm guessing that it is generated as a part of the gui builder. I'd ask if this was the case, but I can't comment yet. If you select a generated object in the GUI editor, on the right there is a tab "code" that can be used to modify the grayed out area of the code.

NetBeans 生成的组件具有不可修改的代码,我猜它是作为 gui 构建器的一部分生成的。我会问是否是这种情况,但我还不能发表评论。如果在 GUI 编辑器中选择生成的对象,则右侧有一个选项卡“代码”,可用于修改代码的灰色区域。

Here:
Code tab that is used to modify generated code.

这里:
用于修改生成的代码的代码选项卡。

回答by Andre Timoti

I've come across this problem... been puzzled for the past 2 days.. then I open the source (.java file) with sublime, change the code, save, and it works wonders... I'm laughing when I see this works... think outside the box really works...

我遇到了这个问题......过去2天一直困惑......然后我用sublime打开源(.java文件),更改代码,保存,它产生了奇迹......我在笑我看到这有效......认为跳出框框真的有效......