Java return value (in try/catch clause)(Java 返回值(在 try/catch 子句中))
问题描述
每个人.我有一个关于java中返回值的菜鸟问题.这是我的代码.
everyone. I have a rookie question about the returning value in java. Here's my code.
@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 报告此方法必须返回 long 类型的结果"错误.然而,我确实在 try 块中返回了 tid;eclipse 建议在 try/catch 块之后添加一个返回值,这会破坏逻辑.你能告诉我这里有什么问题吗?谢谢.
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.
推荐答案
当抛出 JMSException
时,返回值未定义.当抛出异常时,控制立即传递给异常处理程序.在这种情况下,您记录错误.然后控制从该点继续进行,直到函数结束而不返回值.你要么需要返回一个值,要么抛出一个异常.
When a JMSException
is 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.
这篇关于Java 返回值(在 try/catch 子句中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java 返回值(在 try/catch 子句中)


基础教程推荐
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- Java Swing计时器未清除 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01