Catching exception and throwing the same?
Asked Answered
E

7

3

Could you please tell me which approach is better in below two code blocks?

catch (MyException e) {
    throw new MyException ("Error processing request", e);
}

Or

catch (MyException e) {
    throw e;
}
Ekaterinoslav answered 7/1, 2014 at 6:58 Comment(5)
aren't you the same guy who just asked a similar question and had his topic closed even though we told you exactly how try/catch/throw and throws work? edit: never mind!Syllabi
I would vote for the first approach.. Generally, you catch many exceptions, generalize them into one and throw it.. So that all similar exceptions can be handled in the same way..Smithery
@DanPantry - No.. He isnt.. That guy's reputation was less (I think).. :PSmithery
option two is a NOP..Dhow
By which @RC. means that there is no point catching and then immediately re-throwing the same exception without doing anything else in the meantime. You may as well just not catch the exception and let it propagate naturally. Of course if you do something else, additionally, in the catch block, there may be a reason for this. How about make that explicit?Sup
F
5

In order to compare two approaches, they should do the same thing. These two do not do the same thing.

The first approach would be better because you would change its message to a more user friendly one. Perhaps you could also log it (stacktrace or whatever...) before rethrowing it.

The second approach is better regarding performance. Actually, it would be even better if you did not catch the exception at all and let it throw it self.

You have to choose what is preferable, based on user experience and perhaps logging or performance. By default (and not always) I would choose the first.

Hope I helped!

Finnigan answered 7/1, 2014 at 7:2 Comment(0)
E
1

I do not see point in catching the exception and throwing it again. Once rare scenario could be that you need to perform some operation when the exception has occurred but at the same time report the exception to the caller to take appropriate action.

If this is the case then, first approach is better because you are just throwing the same exception again (instead of creating a new once). Btw, both the approaches will preserve the stack trace, just the case is that first one will avoid creation of unnecessary object.

Eg:

catch (MyException e) {
  // May be perform some clean-up activity and throw
    throw new MyException ("Error processing request", e);
}
Exteroceptor answered 7/1, 2014 at 7:5 Comment(0)
S
0

Preserve the inner exception, and I don't have an issue. Although, I don't think it makes sense to catch and then rethrow like that. Surely it would be better to just throw a custom-made exception?

Syllabi answered 7/1, 2014 at 7:1 Comment(5)
No.. It makes sense... In your function you can have 5 different try-catch blocks at different places to handle different exceptions (one for FileNotFound, another for ArrayIndexOutOfBounds another for some other file related problem..) Now, we can handle FileNotFound and someother file related exception by rethrowing a generalized FileBasedException.. and arrayIndexOutOfBounds by rethrowing some other common exception... This way, we can just declare that the function throws the exception category and force the caller to do all the thinking...Smithery
Why bother? Just let the exception propogate naturally in that case. If you're getting AIOOB/File exceptions, etc, you shouldn't "hide" that in another exception - just let it be caught at a higher level.Syllabi
We are not hiding... we are generalizing it.. We can throw the parent exception for all child class exceptions and let the caller handle them in the same way.. Its thought of as a better approach...Smithery
I can see that, but I think an Exception like that would be something you would want to handle specifically (if it's expected) or not generallize it (if it's not expected) because one of those Exceptions indicate something bad going wrong. However, I do see your viewpoint and I assume this is just going to be opinion vs opinion so we'll leave it here :PSyllabi
Opinion Vs Opinion..I agree :PSmithery
M
0

What ever the case you can keep StackTrace, there is no issue. But it should be meanning full,there is no point catch and throw same Exception.

Mcevoy answered 7/1, 2014 at 7:2 Comment(0)
M
0

You can wrap the original exception like in your first option if you want to include any additional useful information for calling methods.

Minton answered 7/1, 2014 at 7:10 Comment(0)
R
0

The first one, because the second approach (rethrow the same exception without any processing) is useless.

Typically you need to define exception processing at start of project. Will you use checked or unchecked exceptions? Will you use standard or your custom exceptions? How will you use exception inheritance? Where will you process (log) exceptions? What are information to pass in exceptions. Once you answear such questions, then it is time to start building your API.

Robson answered 7/1, 2014 at 7:17 Comment(0)
P
0

option 1 is useful if you want to change the exception message (or type) while keeping the stack trace.
option 2 is useful if you want to do something before the original exception bubbles up to the caller:

catch (Exception e) {
    // do some cleanup, e.g. close and remove temp files
    // write something to the console or logger
    throw e;
}

If the 'do some cleanup' might throw exceptions by itself, you can put it into another try/catch and ignore/handle them while the caller will have the original exception presented.

There's another situation: if you have a lot of possible exceptions in your try block and want to ignore all but a specific one, you cannot make a 'catch all but...', but you can check the exception class (or have a specific catch block) and re-throw the one(s) you don't want to ignore.

catch (SpecificException e) {
    throw e;
} catch (Exception e) {}
Perfectionist answered 13/9, 2024 at 11:48 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.