Java 返回值(在 try/catch 子句中)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10125941/
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-30 23:42:37  来源:igfitidea点击:

Java return value (in try/catch clause)

javatry-catchreturn

提问by magicbacon

everyone. I have a rookie question about the returning value in java. Here's my code.

每个人。我有一个关于java中返回值的菜鸟问题。这是我的代码。

@Override
public long addDrugTreatment(long id, String diagnosis, String drug,
        float dosage) throws PatientNotFoundExn {
    try {
        Patient patient = patientDAO.getPatientByDbId(id);
        long tid = patient.addDrugTreatment(diagnosis, drug, dosage);

        Connection treatmentConn = treatmentConnFactory.createConnection();
        Session session = treatmentConn.createSession(true, Session.AUTO_ACKNOWLEDGE);
        MessageProducer producer = session.createProducer(treatmentTopic);

        TreatmentDto treatment = null;
        ObjectMessage message = session.createObjectMessage();
        message.setObject(treatment);
        producer.send(message);

        return tid;
    } catch (PatientExn e) {
        throw new PatientNotFoundExn(e.toString());
    } catch (JMSException e) {
        logger.severe("JMS Error: " + e);
    }
}

Eclipse reports a "This method must return a result of type long" error. Yet I did return the tid in the try block; eclipse suggests to add a return value after the try/catch block, which would break the logic. Could you please tell me what wrong here? Thanks.

Eclipse 报告“此方法必须返回 long 类型的结果”错误。但是我确实在 try 块中返回了 tid;eclipse 建议在 try/catch 块之后添加一个返回值,这会破坏逻辑。你能告诉我这里有什么问题吗?谢谢。

回答by D.Shawley

When a JMSExceptionis thrown the return value is undefined. When an exception is thrown, control passes immediately to the exception handler. In this case, you log the error. Then control continues from that point which goes to the end of the function without returning a value. You either need to return a value or throw an exception.

当 aJMSException被抛出时,返回值是未定义的。当抛出异常时,控制立即传递给异常处理程序。在这种情况下,您记录错误。然后控制从那个点继续,直到函数的末尾而不返回值。你要么需要返回一个值,要么抛出一个异常。

回答by Tudor

In Java (or any other C-like language) all control paths must return a value.

在 Java(或任何其他类似 C 的语言)中,所有控制路径都必须返回一个值。

If an exception is thrown inside the trythen the returnwill not be executed and so you are not returning a value on all possible control paths.

如果在内部抛出异常tryreturn则将不会执行,因此您不会在所有可能的控制路径上返回值。

You have to either:

您必须:

  1. add a returnafter the try-catchor
  2. add a returninside each catchor
  3. add a finallywith a return.
  1. returntry-catch或之后添加
  2. return在每个内部添加一个catch
  3. 添加finally一个return.

回答by t0s6i

catch (JMSException e) {
        logger.severe("JMS Error: " + e);
        //You need to throw exception here or return something
        //better would be throw new Exception("JMS Error: " + e);
    }

回答by A_M

There's a route through your code which means there would be no return value defined, which is an error, since your method says you'll always return a long.

有一条通过您的代码的路由,这意味着没有定义返回值,这是一个错误,因为您的方法说您将始终返回 long。

Are you expecting a value to be returned when if the code throws a JMSException? If so, perhaps declare tld outside the try with a default value.

如果代码抛出 JMSException,您是否希望返回一个值?如果是这样,也许可以使用默认值在 try 之外声明 tld。

Else did you really mean to re-throw the JMSException?

否则你真的想重新抛出 JMSException 吗?

回答by timash11

The problem here is that with methods no matter which route the code takes it must return the type specified if execution of the method completes. So your problem in this code is the second catch. The first catch throws an error and therefore the method does not complete execution and thus does not need a return statement. However in your second catch you just print an error so the method will execute till the end so must therefore return a long. The way to solve this is to either put an appropriate long for your code to be returned in the second catch or to throw the JMSException and deal with that in the code that calls this method. Note if you throw in the catch you will have to add the throw to your method declaration.

这里的问题是,无论代码采用哪条路径,方法都必须在方法执行完成后返回指定的类型。所以你在这段代码中的问题是第二个问题。第一个 catch 抛出错误,因此该方法没有完成执行,因此不需要 return 语句。但是,在您的第二个捕获中,您只是打印一个错误,因此该方法将执行到最后,因此必须返回一个 long。解决此问题的方法是为要在第二个捕获中返回的代码放置适当的 long,或者抛出 JMSException 并在调用此方法的代码中处理该异常。请注意,如果您抛出 catch,则必须将 throw 添加到您的方法声明中。

回答by Jim

Let's imagine a JMSException was thrown:

让我们想象一个 JMSException 被抛出:

@Override
public long addDrugTreatment(long id, String diagnosis, String drug,
        float dosage) throws PatientNotFoundExn {
    try {
        Patient patient = patientDAO.getPatientByDbId(id);
        long tid = patient.addDrugTreatment(diagnosis, drug, dosage);

        Connection treatmentConn = treatmentConnFactory.createConnection();
        //JMS thrown above. No code from here gets executed
    } catch (PatientExn e) {
        throw new PatientNotFoundExn(e.toString());
    } catch (JMSException e) {
        logger.severe("JMS Error: " + e);
    }
}

In the above if a JMSException is thrown no part of the code returns a long.

在上面,如果抛出 JMSException,则代码的任何部分都不会返回 long。