5

Does anyone know if there is a way to generate different code in the catch block automatically depending on the exception?

The Eclipse function 'Surround with try/catch' generates a try/catch block which just includes dumping a stack trace.

I'm doing a bunch of similar things in the code and so most of my exceptions will boil down to probably three or so different types. I'd like to have different catch block code for each one and have eclipse auto format based on the exception.

For example: if my code generates a RemoteConnectionException I'd like to display a dialog to the user to reconnect. If it generates a RemoteContentException I'd like to log it.

(I made these up.)

Thanks in advance

UPDATE: I've been poking around and have two potential solutions.

1) I've found something called the fast code plugin which might do what I'm looking for. http://fast-code.sourceforge.net/index.htm

2) For specifically handling exceptions I'll probably just write a generic exception handler and modify the catch block code to pass the exception to that instead of printing the stack trace. Then the java code will determine which action to take based on exception type.

TheSporkboy
  • 1,759
  • 1
  • 13
  • 13

2 Answers2

4

Templating has it's limits. However your problem can be solved very elegantly with Aspect. ( http://www.eclipse.org/aspectj/ ) Just create a new annotation for every type of "template-case" you need and use an around advice.

Ps: don't use printStackTrace() to syserr/sysout. There are so many production grade, lightweight logging frameworks.... pleeeaseee... don't abuse poor little System.out/err :)

EDIT:

Some example for a logging / benchmarking advice. (note: I'm using spring AOP for aspects, and lombok for easy access to the logging framework. The getCurrentUser() code is not really relevant here, it's just for getting the current user from Spring Security)

package com.XXXXXXXX.aspects;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

@Component
@Aspect
@Slf4j
public class LoggerAspect {

    private final static String DOMAIN = "XXXXXXXX";

    private static String getCurrentUser() {
        String username = "Unknown";
        try {
            Object principal = SecurityContextHolder.getContext().
                    getAuthentication().
                    getPrincipal();
            if (principal instanceof UserDetails) {
                username = ((UserDetails) principal).getUsername();
            } else {
                username = principal.toString();
            }
        } catch (Exception e) {
        }
        return username;
    }

    @Pointcut("within(com.XXXXXXXX.services..*)")
    public void inServiceLayer() {
    }

    @Pointcut("execution(* getMatcherInfo(..)) || execution(* resetCounter(..))")
    public void notToAdvise() {
    }

    @Around("com.XXXXXXXX.aspects.LoggerAspect.inServiceLayer() && !com.XXXXXXXX.aspects.LoggerAspect.notToAdvise()")
    public Object doLogging(ProceedingJoinPoint pjp)
            throws Throwable {
        long start = System.nanoTime();
        StringBuilder sb = new StringBuilder(DOMAIN);
        sb.append('/').
                append(getCurrentUser()).
                append(" accessing ").
                append(pjp.getSignature().
                getDeclaringTypeName()).
                append('.').
                append(pjp.getSignature().
                getName());
        log.trace("START: " + sb.toString());
        Object retVal = pjp.proceed(pjp.getArgs());
        long duration = System.nanoTime() - start;
        log.trace("STOP: " + duration / 1000000 + " msec. " + sb.toString());
        return retVal;
    }
}
Gergely Szilagyi
  • 3,813
  • 1
  • 14
  • 12
  • Getting rid of that stupid print stack trace is exactly why I want to customize the template. ^_^ I've been in operations for more than a decade and I'm appalled at how often developers dump a stack trace when they should be handling the exception. I can understand it if it's something totally unexpected but you know, when you're accessing a file for example. There are some expected failure cases which are easily handled. ^_^ – TheSporkboy Jul 02 '12 at 22:57
  • What is Aspect? Aspect4j? I'm looking it up but what I see I'm not sure is what you're talking about. – TheSporkboy Jul 02 '12 at 22:59
  • @user1497207: added an aspect link to the answer – Gergely Szilagyi Jul 02 '12 at 23:04
  • @GergelySzilagyi Can you elaborate how to use aspects here? Which joinpoint should have the around advice? What should the advice contain? (Can you please tag me on response so I get a notification? Thanks) – Miserable Variable Jul 02 '12 at 23:26
  • @MiserableVariable: a full Aspect-primer won't fit into the comment box, but I try to point you to the right direction. This example http://www.eclipse.org/aspectj/doc/released/progguide/language-anatomy.html#an-example-aspect is almost ready for the current question, though it uses separate before and after advices instead of an around one, but it doesn't really matter in this situation. – Gergely Szilagyi Jul 02 '12 at 23:36
  • Thanks for updating and adding the link. Aspect looks handy. – TheSporkboy Jul 02 '12 at 23:42
  • @GergelySzilagyi I do have some background using AspectJ. Thanks for the link. Are you suggesting that all functions should be advised and when they throw exception appropriate actions should be taken depending on concrete type of the exception? – Miserable Variable Jul 02 '12 at 23:52
  • @MiserableVariable: No. Absolutely not. That would decouple the error handling from the source of error too much in my opinion. What I do is this: expected expection: log and handle with error specific code, unexpected exception: log with aspect, expected unchecked exception: log and rethrow with an aspect. – Gergely Szilagyi Jul 02 '12 at 23:55
  • Yes, that is what I was thinking. But I am still unable to understand your approach, this must be my more-then-usually-stupid day. Can you please add some sample code to your answer? – Miserable Variable Jul 02 '12 at 23:57
  • @MiserableVariable: added a simple logging example based on aspects to the answer. Using custom annotations is a bit more flexible, but I didn't wanted to paste more than one source file here. – Gergely Szilagyi Jul 03 '12 at 00:10
0

I'm not sure if there is such an option available in eclipse. I've been using the surround with try/catch option for quite sometime now and it always dumps the default e.printStackTrace() line in the catch block for the Exception e.

Prash
  • 39
  • 6
  • You can change the template but cannot make it exception specific. I usually change it to something that gives me compilation error (so that I am forced to add a catch block) – Miserable Variable Jul 02 '12 at 23:28