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.
相关文章