Java return value (in try/catch clause)
Solution 1
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.
Solution 2
In Java (or any other C-like language) all control paths must return a value.
If an exception is thrown inside the try
then the return
will not be executed and so you are not returning a value on all possible control paths.
You have to either:
- add a
return
after thetry-catch
or - add a
return
inside eachcatch
or - add a
finally
with areturn
.
magicbacon
Java Developer, interesting in all kinds of computer technologies.
Updated on June 27, 2022Comments
-
magicbacon almost 2 years
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 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.
-
aglassman about 12 yearsThis is correct, but a little more explanation may be helpful. In the case catching a PatientExn, you throw that, so no return value is needed. In the case of JMSException, you log an error, and continue method execution, from the END of the try/catch block. Therefore the return statement will never be reached. You need another return statement either in the JMSException catch block, or at the end of the method. Or throw JMSException, if you do not want to return a value.
-
michelson about 12 years@aglassman: I was debating whether I should explain more or not. I guess that I should :)
-
magicbacon about 12 yearsThanks. I think I understand now. Thanks everyone!