Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Throwing exceptions

Tags:

java

exception

Is it a good idea to pass an object to a constructor when throwing an exception?

Let's imagine that there is next code somewhere in service package.

throw new MyException(object);

MyException class:

Object object;
public MyException(Object object) {
    super();
    this.object = object;
}

public Object getObject() {
    return object;
}

And later, let's say, in GUI we have to handle the exception thrown in service. We just catch an exception and want to access object passed in the constructor. This works. But is it a correct from the point of style?

Is the use of getObject() a correct approach?

like image 596
positiveAlex Avatar asked May 23 '26 22:05

positiveAlex


1 Answers

I would say it depends on what you are doing with getObject. If you are just using it to report the error or manage the recovery from the exception then there's nothing wrong with this. I would pass something more specific than an object. For example, I might give the exception information about the cause of the error and capture any useful information that might help solve the error.

If, on the other hand, you are using this object to continue some normal branch of control flow, then that wouldn't be considered a normal use of exceptions! To repeat the obvious, exceptions are for exceptional situations and nothing more. If you're doing something else with them it's generally bad idea.

If you are using an exception to capture results that you are processing later then that's a bad design smell. Look at refactoring your code to write those objects out to a store for processing later, or some such. Don't abuse exceptions.

like image 183
Jeff Foster Avatar answered May 25 '26 12:05

Jeff Foster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!