Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
364 views
in Technique[技术] by (71.8m points)

design patterns - Where do you like to catch exceptions and why?

Where do you like to catch exceptions and why?

I'm interested in seeing where people find it useful to put their try/catch blocks in the hope that some general patterns might emerge. I'll post my two example answers in C++ but any language is fine.

One location and reason per answer please. Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Don't catch anything that you are not prepared to and able to handle.

So, have top-level exception handling in place to bomb the application the way you like on unexpected exceptions and then only catch the stuff you need (as close to where it might be occuring) to get the functionality that is needed.

And you should do only one of two things: actually do something to solve/work around the problem or rethrow a more descriptive exception that has the caught exception as its innerException.

EDIT: If you need a finally block (e.g. to release something you allocated in your code) and you don't have anything useful to do with any exceptions that might pop up the same logic applies: simply don't handle them. Instead, use a catch { throw; } to rethrow the exception to a higher level while keeping all exception info intact. (Or simply omit the catch block, which I think/hope does the same thing?)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...