Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrap exceptions by runtime exceptions with an annotation

Is there a way to annotate a method so all exceptions thrown are converted to runtime exception automagically?

@MagicAnnotation
// no throws clause!
void foo()
{
  throw new Exception("bar")'
}
like image 654
ripper234 Avatar asked Jun 27 '09 10:06

ripper234


People also ask

How do you wrap an exception?

Wrapping exception simply involves setting the InnerException property of the new exception to propagate up the call stack, to the caught exception. Doing this maintains the exception call stack information. You can see that the caught exception was the ArithmeticException and it had the defined error message.

How do you wrap checked exceptions in Java?

You can write a helper function to convert thrown exceptions to unchecked ones. Essentially you would call something like callUnchecked(() -> getConfigFactory()) in your code and define callUnchecked similar to try { return supplier. get(); } catch (Throwable ex) { throw new RuntimeException(ex); } .

Can try catch block be annotated?

2. Re: try catch around annotated method. Right approach, but Seam doesn't support method level interceptors, only class level interceptors. So you can attach the interceptor at class level, and then mark the method with the same annotation, and only intercept those.


1 Answers

Project Lombok's @SneakyThrows is probably what you are looking for. Is not really wrapping your exception (because it can be a problem in a lot of cases), it just doesn't throw an error during compilation.

@SneakyThrows
void foo() {
    throw new Exception("bar")'
}
like image 155
sinuhepop Avatar answered Oct 22 '22 03:10

sinuhepop