Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

exception handling - Usage of try/catch blocks in C++

In general, I tend to use try/catch for code which has multiple failure points for which the failures have a common handler.

In my experience, this is typically code which qualifies input or context before performing some action or output after performing some action.

I have received counsel from literature and colleagues to minimize the code in such blocks and I accept that as generally good advice.

I would like to understand a bit more about the foundation for the above advice:

  • What is the nature of the overhead?
  • Are there recent development guidelines that address the recommended usage (or avoidance) of try/catch blocks?
  • How much do faster processors and more modern compilers mitigate the problems with try/catch?

Thanks in advance for the help,

AJ

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

In c++, the cost depends on the implementation. In general, there are two ways to implement exceptions:

The first is the "table" approach. The compiler builds a set of tables to look up, at the point where the exception is thrown, where to go. When the exception is thrown, it has to search through each table up the call stack until it finds something that will catch this exception. Since this is all runtime based, entering or exiting a try catch produces no penalty (good) but throwing an exception involves potentially many lookups, producing a much slower throw. I personally prefer the not-having-to-pay for try catch blocks, because exceptions should be a very rare circumstance. This also would make executables larger, if they have to store the tables.

The seconds is the "code" approach. Each time the code enters a try catch block, conceptually, the location of the block is pushed onto a stack. This produces a cost during entering and exiting a try-catch block, however, when an exception is thrown, the runtime mechanism can quickly pop off the stack to find where to go. So, throwing exceptions is (much?) faster, but entering a block now has a cost. Putting a try catch block in a tight low level loop could produce significant overhead.

You would have to check your specific compiler to see which one they use.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...