For example, I need to get a Foo object using getFoo() method:
Foo foo = getFoo();
After this, I want to handle the case that getFoo() didn’t return a Foo object successfully. This in turn includes two cases:
- getFoo() throws an exception.
- The return result of getFoo() is null, empty String, 0, or whatever should be treated as “Empty result”.
Ideally I would want getFoo() throw an exception instead of returning an empty result, but sometimes that may be a call to a method in another package which I don’t own.
These are methods that I can think of:
1. Duplicate handling code
Foo foo = null;
try {
foo = getFoo();
} catch (ResourceNotFoundException ex) {
logger.warn("blablabla");
foo = defaultFoo;
someOtherComplicatedStuff();
}
if (null == foo) {
logger.warn("blablabla");
foo = defaultFoo;
someOtherComplicatedStuff();
}
This is definitely not a good idea.
2. Move handling logic to an individual function
Foo foo = null;
try {
foo = getFoo();
} catch (ResourceNotFoundException ex) {
handleNullFoo(var1, var2, var3, var4);
}
if (null == foo) {
handleNullFoo(var1, var2, var3, var4);
}
The problem is the logic may use a lot of local variables. Passing these variables to the external function doesn’t make much sense. Worse, some of the variables may need to be modified during this process. I don’t think modifying arguments in a function is a good practice, not to mention the issue it may cause if an argument is primitive typed.
3. Throw a fake exception
Foo foo = null;
try {
foo = getFoo();
if (null == foo) {
throw new ResourceNotFoundException();
}
} catch (ResourceNotFoundException ex) {
logger.warn("blablabla");
foo = defaultFoo;
someOtherComplicatedStuff();
}
This is by far the cleanest way, but it is more like a kind of hack. It may not proper to throw a ResourceNotFoundException in a package the exception class doesn’t belong to. It also decreases the readability of the code as people may not realize that the exception is handled inside the function.
So, what’s your suggestion?
Thank you very much!
Here is another alternative:
Note that the
foo = null;in thecatchclause is almost certainly unnecessary. It is only needed if there’s some code afterfoo = getFoo()that can throwResourceNotFoundException.