8

To work with multiple methods i have to use the same checked exception catch many times (see Java: checked vs unchecked exception explanation). The result is duplicated lines of code. I would like some way of reducing the duplicated exception catch to reduce the number of lines of code.

What is a good way to reduce the number of duplicated catch sections and decrease the lines of code? Is there any way that I can write that catch operation in one another file and use that explicitly?

Basically i want to reduce line count and make the code more concise and easier to read.

Here is an example of my code:

@RequestMapping(value="")
public @ResponseBody Response addMultiple(){
if() {
    try {
        data = new weight();

    } 
    catch( AmazonServiceException se ){
        response = x;
    }
    catch (AmazonClientException ce) {
        response = y;
    }
    catch(JsonProcessingException je) {
        response = z;
    }
}


@RequestMapping(value="")
public @ResponseBody Response addMultiple2(){
if() {
    try {
        data = new height();

    } 
    catch( AmazonServiceException se ){
        response = x;
    }
    catch (AmazonClientException ce) {
        response = y;
    }
    catch(JsonProcessingException je) {
        response = z;
    }
}

@RequestMapping(value="")
public @ResponseBody Response addMultiple3(){
if() {
    try {
        data = new age();

    } 
    catch( AmazonServiceException se ){
        response = x;
    }
    catch (AmazonClientException ce) {
        response = y;
    }
    catch(JsonProcessingException je) {
        response = z;
    }
}

I want declare that exception catching operation once, and want to call it multiple time.

I am using Spring framework.

Roman C
  • 49,761
  • 33
  • 66
  • 176
ravi_s
  • 145
  • 2
  • 7

4 Answers4

3

A general way to handle it could be to create a method that can handle all your exception types and return a Response object based on the passed in Exception.

The handleException method:

public static Response handleException (Exception e)
{
    Response res = null;

    if (e instanceof AmazonServiceException)
    {
        res = x;
    }
    else if (e instanceof AmazonClientException)
    {
        res = y;
    }
    else if (e instanceof JsonProcessingException)
    {
        res = z;
    }
    else // if we get any other exception
    {
        res = xyz;
        // OR you can throw new RuntimeException(e);
    }
    return res;
}

Now, all the calling code where you don't want to repeat all the exception handling would use it like this:

@RequestMapping(value="")
public @ResponseBody Response addMultiple(){
    if() {
        try {
            data = new weight();
        } 
    // Use this same catch block in the other addMultiple() methods
    catch(Exception e)
    {
        response = handleException(e);
    }
}
Michael Markidis
  • 4,163
  • 1
  • 14
  • 21
  • Michael, I am curious to know if at this year (2019) and with all the changes to the language, do you still think this is the best solution or do you think that we could use something different now? Thanks! – jfajunior Apr 25 '19 at 07:38
1

You'd write a custom exception handler in Spring if you want to handle these exception and take some action, the handler will take if there any exception occurs, also you can omit the try-catch blocks.

@ExceptionHandler({ Exception.class }) //narrow it to the exception you need
    public ModelAndView globalExceptionHandler(Exception e) {
        return new ModelAndView("error");
    }

Otherwise catch Exception in your methods and write a handler method to handle it in catch block.

change catch block with

catch( Exception e ){
    handleException(e);
}

and handler below

private Response handleException(Exception e){
    if(e instanceof E1){

    }else if(e instanceof E2){

    }
    .
    .
    .
    return response;
}
Saravana
  • 12,647
  • 2
  • 39
  • 57
1

The answer of @UUID will allow you to handle exceptions outside the context of the function. If you want to handle them inside the function, you can write a handleException method, that will allow you return values and have parameters:

public class ExceptionHandler {

    public static Response handleWebException(Object ... parameters) {
        return ... some result ...;

    }
}

In your method you call

public @ResponseBody Response addMultiple2(){
    if() {
        try {
            data = new height();

        } 
        catch( Exception ex ){
            return ExceptionHandler.handleWebException(ex);
        }
    }
}
thst
  • 4,592
  • 1
  • 26
  • 40
0

Write a custom exception handler class, where you can pass the exception and use it across all the classes

Basically something like this that would handle any exception and can be used across all classes.

  @ExceptionHandler(Exception.class)
  public ModelAndView handleError(HttpServletRequest req, Exception exception) {
    logger.error("Request: " + req.getRequestURL() + " raised " + exception);

    ModelAndView mav = new ModelAndView();
    mav.addObject("exception", exception);
    mav.addObject("url", req.getRequestURL());
    mav.setViewName("error");
    return mav;
  }