[ part 1 ]
error_code vs error_condition
Of the 1000+ pages of C++0x draft, the casual reader is bound to notice one thing: error_code and error_condition look virtually identical! What's going on? Is it a copy/paste error?
It's what you do with it that counts
Let's review the descriptions I gave in part 1:
- class error_code - represents a specific error value returned by an operation (such as a system call).
- class error_condition - something that you want to test for and, potentially, react to in your code.
The classes are distinct types because they're intended for different uses. As an example, consider a hypothetical function called create_directory():
void create_directory(
const std::string& pathname,
std::error_code& ec);
which you call like this:
std::error_code ec;
create_directory("/some/path", ec);
The operation can fail for a variety of reasons, such as:
- Insufficient permission.
- The directory already exists.
- The path is too long.
- The parent path doesn't exist.
Whatever the reason for failure, after create_directory() returns, the error_code object ec will contain the OS-specific error code. On the other hand, if the call was successful then ec contains a zero value. This follows the tradition (used by errno and GetLastError()) of having 0 indicate success and non-zero indicate failure.
If you're only interested in whether the operation succeeded or failed, you can use the fact that error_code is convertible-to-bool:
std::error_code ec;
create_directory("/some/path", ec);
if (!ec)
{
// Success.
}
else
{
// Failure.
}
However, let's say you're interested in checking for the "directory already exists" error. If that's the error then our hypothetical caller can continue running. Let's have a crack at it:
std::error_code ec;
create_directory("/some/path", ec);
if (ec.value() == EEXIST) // No!
...
This code is wrong. You might get away with it on POSIX platforms, but don't forget that ec will contain the OS-specific error. On Windows, the error is likely to be ERROR_ALREADY_EXISTS. (Worse, the code doesn't check the error code's category, but we'll cover that later.)
Rule of thumb: If you're calling error_code::value() then you're doing it wrong.
So here you have an OS-specific error code (EEXIST or ERROR_ALREADY_EXISTS) that you want to check against an error condition ("directory already exists"). Yep, that's right, you need an error_condition.
Comparing error_codes and error_conditions
Here is what happens when you compare error_code and error_condition objects (i.e. when you use operator== or operator!=):
- error_code against error_code - checks for exact match.
- error_condition against error_condition - checks for exact match.
- error_code against error_condition - checks for equivalence.
I hope that it's now obvious that you should be comparing your OS-specific error code ec against an error_condition object that represents "directory already exists". C++0x provides one for exactly that: std::errc::file_exists. This means you should write:
std::error_code ec;
create_directory("/some/path", ec);
if (ec == std::errc::file_exists)
...
This works because the library implementor has defined the equivalence between the error codes EEXIST or ERROR_ALREADY_EXISTS and the error condition std::errc::file_exists. In a future instalment I'll show how you can add your own error codes and conditions with the appropriate equivalence definitions.
(Note that, to be precise, std::errc::file_exists is an enumerator of enum class errc. For now you should think of the std::errc::* enumerators as placeholders for error_condition constants. In a later part I'll explain how that works.)
How to know what conditions you can test for
Some of the new library functions in C++0x have "Error conditions" clauses. These clauses list the error_condition constants and the conditions under which equivalent error codes will be generated.
A bit of history
The original error_code class was proposed for TR2 as a helper component for the filesystem and networking libraries. In that design, an error_code constant is implemented so that it matches the OS-specific error, where possible. When a match is not possible, or where there are multiple matches, the library implementation translates from the OS-specific error to the standard error_code, after performing the underlying operation.
In email-based design discussions I learnt the value of preserving the original error code. Subsequently, a generic_error class was prototyped but did not satisfy. A satisfactory solution was found in renaming generic_error to error_condition. In my experience, naming is one of the Hardest Problems in Computer Science, and a good name will get you most of the way there.
Next up, a look at the mechanism that makes enum class errc work as error_condition placeholders.
234 comments:
«Oldest ‹Older 201 – 234 of 234I found this article very helpful and motivating. The way the topic is explained makes it accessible for everyone. Looking forward to reading more thoughtful posts like this soon. wine tasting naperville
Sreenivasa Constructions develops residential and commercial spaces in Hyderabad.
tattva developers is a top real estate company in Hyderabad offering Ultra Luxury 4BHK Villas in Patancheru and villa plots for sale in Patancheru.
This is a clear and insightful explanation of the distinction between error_code and error_condition, especially for developers navigating the complexities of modern C++. The practical examples really help illustrate why the separation matters and how to handle errors more robustly across platforms. Thoughtful breakdowns like this make tricky concepts much easier to grasp much like applying the right auto base coat paint ensures a smooth and reliable finish.
Gowra Greendale by Gowra Ventures offers premiumplots for sale in kompally within a well-planned gated community. Featuring HMDA approval, modern infrastructure, wide roads, and lush green landscapes, it ensures a peaceful lifestyle with excellent connectivity. Ideal for building your dream home or making a smart investment in a fast-growing location.
This article brilliantly breaks down asynchronous thinking in C++, making complex concepts like system error handling in C++0x approachable. The examples are clear, practical, and insightful, providing a solid foundation for both beginners and experienced developers looking to enhance their skills.
Vajram Ixora offersluxury 3bhk gatted community aprtments in nalagandla, Hyderabad, with modern amenities, spacious homes, and excellent connectivity.
Candeur Crescent is a modern residential community offering luxury 3bhk flats for sale in serlingampally near gachibowli, designed for comfortable urban living. With spacious layouts, contemporary architecture, and lifestyle amenities, it is counted among the top 3BHK flats for sale in Sherlingampally. The project provides strong connectivity to IT hubs, schools, healthcare centers, and shopping areas, making it ideal for families searching for 3BHK flats for sale in Sherlingampally in Hyderabad.
Great insights on asynchronous design and error handling in modern C++. The explanation makes complex concepts easier to grasp.
Make the most of your 6 hour layover in Nairobi! Explore wildlife, city highlights, and cultural attractions with layoverindubai com’s guided layover services. short trip nairobi kenya
Step into bold street style with the Pink Carhartt Jacket where rugged work wear meets modern fashion edge. Designed for comfort, durability, and standout appeal, this piece brings a fresh pop of colour to any outfit. Whether you're layering up for the city or making a statement outdoors, this jacket delivers confidence in every stitch.
Book 3 Days Golden Triangle Tour from Delhi at best price ₹7,999. Visit Taj Mahal, Agra Fort & Jaipur. Check itinerary & book now with My Satya Travels.
A good read for people looking to venture into internet business. The topics discussed will give insight on key elements such as business model, websites creation, marketing techniques, and many more that will prevent beginners from making mistakes in their ventures.
This is indeed an extremely informative and well-written article on the subject of SEO services offered in Agra. The explanation on various digital marketing techniques along with website ranking methods is very much understandable for all.
Thank you for sharing this vital information.
Check Travel My Kashmir Travel agency for best and affordable Kashmir cab service and Kashmir packages
Book online cabs in Kashmir here < a href="https://travelmykashmir.com/kashmir-cab-service/"> Book Online cab in Kashmir
Thank you for sharing insightful post. custom fifa world cup shirt https://www.etsy.com/shop/nhshopfinds
AGP 40 Cal Arc Clothing gives the impression of gear intended for professionals who cannot afford to compromise when it comes to workplace protection. Durable construction and practical comfort are always valuable features
flame resistant coveralls deliver professional quality protection while supporting productivity in demanding workplaces.
Manish Diwakar Agra SEO Agency is a reliable SEO Agency in Agra providing services like SEO, Local SEO, and Digital Marketing. We provide our clients with improved Google search results and enhanced traffic through ethical SEO methods.
Navanaami is recognized as the best real estate developer in hyderabad, offering premium residential projects with innovative designs, superior construction quality, and world-class amenities. With a focus on sustainability, timely delivery, and customer satisfaction, Navanaami creates exceptional living spaces for modern lifestyles.
Great follow-up to the series. I appreciate how you break down the error handling concepts with practical examples instead of keeping everything purely theoretical. Even though this post is a few years old, the ideas around writing more reliable software are still relevant. Reading it also made me think about how dependable systems are just as important in niche applications like Water Sports marketing software, where stability and smooth performance can make a real difference. Thanks for sharing your expertise!
This article explains C++ system error support with clarity and practical examples. Morpheus Leather Coat A valuable resource for developers wanting to understand asynchronous programming concepts and write more reliable, modern C++ applications.
People like to know about the System error support in C++0x - part 2 to use it and resolve their problems. When I used roof debris removal services I got the helpful ideas that provide us with the best results that we are looking for.
flame resistant coveralls help create safer workplaces by providing trusted protection and all-day comfort.
AGP 40 Cal Arc Clothing is built for professionals who regularly work around electrical hazards. It delivers dependable protection while providing the flexibility and comfort needed for long maintenance and installation projects
Excellent post! This series has been immensely helpful for understanding how to properly extend for custom libraries.
Explaining these technical concepts step-by-step helps developers who are looking to write cleaner, more structured code. On another note, for anyone interested in investing or exploring high-end properties in Florida, consulting with a Miami luxury real estate agent can also be a very interesting resource for specialized guidance.
This is a great breakdown of system_error support and error propagation in C++0x/C++11! Clear, practical explanations of category code handling like this make asynchronous programming and low-level error management so much easier to understand. On a different note, for entrepreneurs who are evaluating buying or selling a company, partnering with a professional business broker kendall can also be a valuable resource to consider.
Understanding system error support and error categories in C++ is essential for building robust, cross-platform applications. Clear explanations of how low-level platform errors translate into manageable error codes make asynchronous programming so much cleaner to work with. On a different note, for entrepreneurs who are evaluating buying or selling a business, consulting with a professional advisory team can also be a valuable resource to consider.
Interesting technical discussion on system error support and how thoughtful error handling can make software more reliable and easier to troubleshoot. Clear solutions matter across many industries. That same focus on dependable guidance and communication is something clients can appreciate when working with Mora Realty Davie.
A clear and helpful explanation of the distinction between error_code and error_condition. The practical create_directory() example makes the concepts much easier to understand, especially for developers learning how C++ handles system errors. Pool service Henderson Nv is an unexpected keyword for a C++ article, but the technical explanation is very useful.
Post a Comment