0

In my java code if the log() method fails still want to proceed with the return of the response message, but the below code fails if the log() fails, i just want the code to work with a response message irrespective of log() method fails or not.

My Code

public class MyClass 
{
    public MyResponse getMyResponse(MyRequest request) throws Exception
    {
        MyResponse response = new MyResponse();
        response=Service.getRes(request);
        log(request,response);
        return response;
    }

    public void log(MyRequest request,MyResponse response)
    {
        Service.log(request,response);
    }
}
Egg_Egg
  • 177
  • 1
  • 11
haja
  • 135
  • 1
  • 4
  • 12

3 Answers3

0

Try using finally.

public MyResponse getMyResponse(MyRequest request) throws Exception
{
    MyResponse response = new MyResponse();
    response=Service.getRes(request);
    try {
        log(request,response);
    }
    catch (Exception e) {
        // Do something with the error?
    }
    finally {
        // No matter if there is an error or not, the following will be executed.
        return response;
    }
}
mbinette
  • 5,094
  • 3
  • 24
  • 32
  • i get a warning "finally block does not complete normally" i assume finally should not have a return – haja Oct 02 '15 at 03:26
  • You can put it after the catch block if you want, as long as you don't throw an exception in the catch block (if you do, your function wouldn't return anything anyway), whatever is after is also going to be executed no matter what. – mbinette Oct 02 '15 at 03:36
0

Use a try-catch-finally in log method. In catch you can do something about the error like print it(I suppose you cannot log it :) !) and in finally you continue with normal course of action.

Dhruv Rai Puri
  • 1,335
  • 11
  • 20
0

If by "fail" you mean that you are getting an exception, you could do this:

public void log(MyRequest request,MyResponse response)
{
    try { Service.log(request,response); } catch(Throwable e) {}
}

This will ignore any exception thrown by the Service.log request.

Michael
  • 401
  • 5
  • 16