1

I have multiple methods in class; each method has been declared with "throws Exception" option. Whenever an exception occurs I want one object present in this class to be wrapped automatically and create a custom exception object.

This newly created custom object is supposed to be thrown.

I don't want to create a try-catch block in every method and create a custom exception object, which would have the object I want to be wrapped along.

Is there a way to do it without above approach. If so what code changes do I need to do?

rghome
  • 8,529
  • 8
  • 43
  • 62
Srinivas P
  • 91
  • 1
  • 4
  • I assume you've heard of composition? – Stultuske Jun 26 '19 at 08:13
  • Your question is a bit unclear as in the first and second paragraph you say you want a custom object and in the third you say you don't. Is it that you just want to avoid the overhead of the try-catch-rethrow code? – rghome Jun 26 '19 at 08:25
  • that's correct @rghome , i want a custom exception's object to be created automatically and not me write try catch code for every method. I had to think of this way, because i m not sure if its possible if we can get the source object on which exception was actually triggered , actually i want one specific object from the list of all classes that are getting listed in the stack trace. – Srinivas P Jun 27 '19 at 09:17

2 Answers2

0

(I assume you are not asking how to define a custom exception class ...)

"Is there a way to do it without above approach."

Not in pure Java. You may be able to do it with AOP or some other technology that will rewrite your bytecodes to inject the "catch-and-wrap-and-throw" logic into your methods.

For example, this article explains how to translate exceptions using AspectJ:

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

I think you can do it with Spring AOP. Something like this:

import org.springframework.aop.ThrowsAdvice;

public class MyExceptionInterceptor implements ThrowsAdvice {

    public void afterThrowing(Method method, Object[] args, Object target, Exception ex) {
        ...
        throw new WrappedException(somehow find object you want to wrap);

Unfortunately, I don't have a lot of experience of using this. This post might help:

How does Spring know that ThrowsAdvice.afterThrowing needs to be called?

There are tutorials online on using "ThrowsAdvice". I suggest checking a few of them.

rghome
  • 8,529
  • 8
  • 43
  • 62