Thursday, April 08, 2010

System error support in C++0x - part 2

[ 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.

130 comments:

  1. Greate post!

    I've once use Asio to wrap MySQL C API and porting MySQL error codes to Boost.System. The tricky part is that, to get an error message, you must pass both the error code *and* the MySQL handle, while you can only specify a simple [error code -> error message] map without any other context information (like the MySQL handle). At last, I had to deprecate the message() method of the corresponding error_category subclass.

    I wonder how can this issue be solved?

    ReplyDelete
  2. Very very very (very) useful explanation! Thank you Chris!

    I am a little confused, why error_category uses `const char*` for `name()` and `std::string` for `message()`... It is bad for embedded.

    ReplyDelete
  3. I simply found your web site some days ago and i are reading through it frequently. you have got a wide range of helpful data on the site and that i conjointly really like the particular type of the site at constant time.data room software

    ReplyDelete
  4. Thank you very much for this post. if you are looking for top Dentist in Reston VA visit here. We have professional staff for all dentistry solutions.

    ReplyDelete
  5. Have you finished the Hootsuite Platform Certification Exam Answers Training Course? Take our test presently to gain your official accreditation—demonstrating your ability to businesses.

    ReplyDelete
  6. contract advantage is Contract Management System offered as SaaS designed to help you do more with your contracts using fewer people, less time, and a smaller budget.

    ReplyDelete
  7. error_code is used for storing and transmitting error codes as they were produced by originating library, unchanged; error_condition is used for performing queries on error_code s, for the purpose of grouping or classification or translation. https://www.unmannedsas.com/

    ReplyDelete
  8. Among the numerous new library includes in C++0x is a little header called . It gives a choice of utilities to overseeing, admirably, framework mistakes. The chief segments characterized in the header are: class error_category. cheap essay writing

    ReplyDelete
  9. Columbia Heights, MN Water Damage Restoration | SERVPRO of Coon Rapids / Central Anoka County:When your Coon Rapids, MN home or business floods, SERVPRO of Coon Rapids / Central Anoka County has the expertise and equipment to properly restore your property.

    Source: Commercial storm damage restoration Columbia Heights

    ReplyDelete
  10. Find Local Musicians to Jam With | Freelance Musicians for Hire Near Me:Whether you are in bands seeking musicians or looking to hire student musicians locally, SoulShare is a unique platform to connect and find other musicians to jam with.

    Source: Bands seeking musicians

    ReplyDelete
  11. From the newest AAA games to multiplayer classics, Elite Gamer has you covered with support for the most popular games. www.floorrefinishingmilwaukee.com/

    ReplyDelete
  12. This information is very important for especially those, who are learning programming. They can solve this issue easily. If you are facing this problem, you should consult with seniors. Masters dissertation writing service.

    ReplyDelete
  13. Hi! Are you interested in crypto trading? You can find an interesting article about cryptocurrency trading here.

    ReplyDelete
  14. Thank you very much for this post. if you are looking for top laser lipo equipment VA visit here. We have professional staff for all dentistry solutions.

    ReplyDelete
  15. Have you ever heard the expression, "The best way to set up an office is by setting up an Office Setup rental?" Well, it seems like operating from home, well, is here to stay as long as there are people. And whether you're one of those fortunate ones who've discarded the two-hour drive down the hallway in favor of some more steps around the office, or you're simply one of those who needs a break, setting up an office rental or setting up a home office setup will make all the difference in the world. Here's what you need to know about office setup.

    ReplyDelete
  16. I think this is an informative post and it is very useful and knowledgeable. therefore, I would like to thank you for the efforts you have made in writing this article :D 먹튀검증

    ReplyDelete
  17. I have read it completely and got really impressed. Love to read more about similar types of articles. Thanks a lot!!

    ReplyDelete
  18. Often when I need to write an essay I use essay rewriting service https://writology.com/rewriting. I can write any essay. I always check my text. It helps me get the best results.

    ReplyDelete
  19. Especially if you’re unfamiliar with the different types jackets and coats than we are here only to provide you our Black Leather L Krasnov Jacket at your doorstep worldwide.

    ReplyDelete
  20. The brake system is an extremely important safety feature on your vehicle. At ALSA Automotive Repair, we understand that a brake system is essential for your safety and that of other drivers. Our experts willCar and truck oil changes Abu Dhabi examine the entire brake system, including the pads / shoes, hydraulic fluids, rotor and drum wear, calipers and wheel cylinders, brake hardware, hoses and pipes, master cylinder and the anti-lock braking system for your car.

    ReplyDelete
  21. Because a russian mail order bride will make your house comfortable and raise your children, you should assist her rather than use force to control her. I am now 29 years old and married to a Russian woman who adores me and will raise my child. I am grateful to these men for allowing me to have a family and continue to aid people all around the world. I want to recommend them to you because they have the potential to alter your life.

    ReplyDelete
  22. Hasten Contracting soil stabilization Houston tx technique is a fast, secure, and cost-efficient solution to create a strong foundation soil stabilization for any type of construction work. While traditional SOIL stabilization in houston soil stabilization methods are not only time-consuming and costly, they are also not very reliable in the long-run, as poor soil conditions can put a whole structure at risk.

    ReplyDelete
  23. A natural aphrodisiac performance sex honey that gives you energy and relief from erectile dysfunction and enhances both female arousal and male performance

    ReplyDelete
  24. We use 1/4-inch backerboard over your level subfloor then lay the tile on top. A flexible underlayment will prevent cracks in ceramic and stone tile because it distributes the weight carried evenly. Tile renovation Edmonton can include new tile installation, floor leveling, tile removal, tile grouting, tile repair, and an assortment of problems for correction.

    ReplyDelete
  25. Vacuuming the interior of the passenger compartment, thorough cleaning and removal of stains from the seats, headrests and armrests, door panels, carpets, the roof of the passenger compartment and the boot. We alsoMobile Car Wash Ottawa have a carpet replacement service; this service will always be on demand and after consulting the availability of brands and models.

    ReplyDelete
  26. Keep sharing such a great article! Are you stuck with your assignment? GoAssignmentHelp is one of the best Nursing Assignment Help service providers that provide best Psychology Assignment Help to those students who face these issues and write nursing assignment help australia and score good grades.

    ReplyDelete
  27. Great Post!I have read all the content of this blog.This is really helpful and informative for me.You are doing a great job.We offer an online How to Write Critical Literature Review.Iam providing this service at a cheap price.

    ReplyDelete
  28. Thanks for this great article. Keep sharing. Foundation companies kansas city

    ReplyDelete
  29. I like this blog very much, Its a rattling nice situation to read and obtain information.
    igoal88 หวย

    ReplyDelete
  30. This is an easy language. If you have a good keyboard, you can type your code pretty faster.

    ReplyDelete
  31. Introducing Chocolates al Khobar, the finest truffles in the region. Finely crafted from the finest ingredients, these delicacies are sureمتجر شوكليت الخبر to tantalize your taste buds with their unique and unparalleled flavour. Offering a gamut of flavours that will have you exploring them all, Chocolates al Khobar truffles are perfect for those who love to indulge. Get ready to feel the love!

    ReplyDelete
  32. as a child, I also really didn’t like writing an essay, it’s good that I had adequate parents who were smart enough to turn to the authors of the essay for help (https://bidforwriting.com/pay-for-essay) . So I had a good childhood<

    ReplyDelete
  33. Looking for a chocolate lover's dream come true? Look no further than truffleers, an online store that specializes in selling chocolate from the city of Dammam. Offering a wide range of flavours and styles, truffleers guarantees thatBuy chocolate gift Dammam you'll never be disappointed in your chocolate purchase. From classic to sinful, truffleers has something for everyone. So don't wait any longer - order your favourite chocolate today from our online store!

    ReplyDelete
  34. Thank you for sharing this great content here. resolutions-av.com/

    ReplyDelete
  35. Executive-Education.id encourages college students to review at your house, having several different optional programs. School, SD, SMP, SMA, College student / General. Area & Schedule based on undergraduate request... go to https://bimbel-calistung.netlify.app/les-privat-calistung-johar-baru.html for further

    ReplyDelete
  36. Great blog. Keep up the good work. milwaukee-fence-installation

    ReplyDelete
  37. Great blog. Keep sharing the nice information. plano foundation repair 9729941555

    ReplyDelete
  38. Pretty amazing website. Keep sharing the good work. it-support-raleigh-nc

    ReplyDelete
  39. Thank you or the inormation. Keep sharing. tulsa-foundation-repair 918-992-4256

    ReplyDelete
  40. I’m extremely pleased to find this website. I really like the knowledge you present here in this article. Visit Us: Kashmir Tour Packages

    ReplyDelete
  41. thanks for sharing this with us we are from Valley trip planner srinagar kashmir based in srinagar founded in 2006 offer all types of budget Kashmir packages also ladakh packages book now

    ReplyDelete
  42. Jabodetabek private tutoring services with teachers coming over to the house. Over a huge selection of active tutors are ready to teach various skills and lessons for kids to adults ... click https://privatmurah.vercel.app/les-privat-kebon-jeruk-murah.html for more information

    ReplyDelete
  43. There could have been the problem with that, but to determine the need of time I would just recommend you mba-assignment that could help you with your assignments and could do the task for you in a much affordable price.

    ReplyDelete
  44. Thanks for this great blog you shared. redwoodroofs.com/

    ReplyDelete
  45. Awesome post you shared, looking forward to seeing more posts here. hebrews34.com/

    ReplyDelete
  46. The system cannot read from the specified device. A device attached to the system is not functioningThe system cannot read from the specified device. A device attached to the system is not functioning

    ReplyDelete
  47. The C language provides several constructs that allow code to run asynchronously. This can be useful for tasks that can't be completed immediately, such as downloading a large file from the Internet. In this article, we'll look at how to use these constructs and some of the benefits they offer. System error support in C 0x is a vital feature for programming and debugging. This feature enables users to trace system errors and to fix them. System error support in C 0x also helps developers debug their code. Click entwickler flutter , I find this very good website online. Thanks

    ReplyDelete
  48. I'm so happy with the content! Thanks for sharing redirect

    ReplyDelete
  49. The system cannot read from the specified device. A device attached to the system is not functioning cost of repair

    ReplyDelete
  50. I enjoy reading this post. Also, thanks for allowing me to comment!

    ReplyDelete
  51. I have been at the look out for such information. Blessed to see this article!

    ReplyDelete
  52. So far you have a great information here. Thank you so much https://careers.tql.com

    ReplyDelete
  53. Srinagar bike rentals & You can Rent a bike in Kashmir that you can book online, drive to all locations in Srinagar Kashmir
    Srinagar bike rentals

    ReplyDelete
  54. I recently visited Kashmir and had a wonderful experience with Srinagar Taxi Service

    ReplyDelete
  55. Is there a way to build it without c++11 or c++0x? Build system is stuck to the older version.

    URL: alphacrimescenecleanupbaltimore.com

    ReplyDelete
  56. PilgrimageTourJune 24, 2023 8:42 pm

    I like you for building a beautiful blog with useful information. I'm hoping you'll provide me further information. Feel Free To Visit Us: Pilgrimage Tour Packages

    ReplyDelete
  57. Awesome post you shared, looking forward to seeing more posts here. end of tenancy cleaning reading

    ReplyDelete
  58. Essay writing service help in providing students with professional assistance in the completion of their academic essays.
    Our services offer a range of benefits, including saving time and reducing stress for students who may be overwhelmed with assignments.
    We provide experienced writers that experts in various subjects and can produce high-quality essays that meet the requirements of the assignment.
    They help students with all aspects of the process of essay writing, from topic selection to research and formatting. Writing services often offer
    additional services such as editing and proofreading to ensure that the final essay is error-free and well-polished.

    ReplyDelete
  59. YEy! this is so impressive! Thank you save here

    ReplyDelete
  60. This is so impressive! Thanks Affidavit of Death

    ReplyDelete
  61. This data is vital for particularly those, who are picking up programming. They can settle this issue without any problem. Assuming that you are dealing with this issue, you ought to talk with seniors.

    ReplyDelete
  62. Great data! Thanks visit us

    ReplyDelete
  63. Thanks for making this content so incredible! www.eokitchen.com/

    ReplyDelete

  64. World SIM card is a practical solution for international travelers seeking seamless mobile connectivity across different countries. It offers the convenience of using a single SIM card for various communication needs, helping you avoid the complexities and costs associated with traditional roaming.

    ReplyDelete
  65. I'm so happy with the content! Thank you https://scottkeeverseo.com/

    ReplyDelete
  66. Thanks for Sharing This Article Your Articles are amazing Also Visit Travelling folks is a leading Travel agents in KashmirBrowse  Kashmir Tour Packages at Best Prices,Travel agents in Ladakh

    ReplyDelete
  67. Diving deeper into the intricacies of system error support in C++0x with part 2 – a valuable resource for developers navigating error-handling in their code. In a parallel vein, Electra cable management system abu dhabi delves into precision in electrical solutions, offering seamless support for your systems.

    ReplyDelete
  68. System error support in C++0x - part 2" is a crucial resource for developers navigating the intricacies of error handling in the evolving C++ landscape. Catering services in Pecos Texas complement your technical endeavors with exceptional catering services. From coding marathons to corporate events, Pecos' catering adds a touch of culinary excellence, ensuring that your gatherings are not only productive but also a flavorful experience for all attendees.





    ReplyDelete
  69. British chocolate is renowned for its rich and velvety texture, combining premium cocoa with traditional craftsmanship. Indulge in the smooth and distinct flavors of شوكولاتة بريطانية for a truly decadent treat.

    ReplyDelete
  70. Soil Stablization Blends in texas enhance soil strength and durability, mitigating erosion and promoting sustainable construction practices for infrastructure projects. These customized blends optimize soil properties, ensuring long-lasting and resilient foundations in the diverse Texas landscape.

    ReplyDelete
  71. Explore the enchanting world of chocolates at متجر شوكليت الرياض in Riyadh, where a delightful array of confections awaits. From artisanal creations to international favorites, this store is a haven for chocolate enthusiasts seeking a sweet escape in the heart of Riyadh.





    ReplyDelete
  72. Thank you for always sharing informative content here. driveway resurfacing

    ReplyDelete
  73. Future Style By Nida Faysal offers a visionary approach to fashion, marrying cutting-edge design with a nod to cultural heritage. With bold creativity and a commitment to pushing boundaries, every garment promises to ignite imagination and redefine the essence of contemporary chic.

    ReplyDelete
  74. The similarities between error_code and error_condition in the C++0x draft are indeed striking. It raises questions about potential oversight or intentional design choices. After delving into such intricacies, take a moment to unwind and relax at the Relax Massage center for a soothing break from technical complexities.

    ReplyDelete
  75. Your content is well-structured; I intend to revisit it later for reference.

    ReplyDelete
  76. Thank you for sharing informative content here. Driveway

    ReplyDelete
  77. Great content you've shared! concrete driveway

    ReplyDelete
  78. In the first part of our discussion on system error support in C++0x (now standardized as C++11), we covered the basics of the std::error_code and std::error_category classes, which provide a standardized way to represent and handle errors in C++ programs. In this second part, we will delve deeper into the additional components introduced in C++0x to enhance error handling, including std::system_error, std::error_condition, and their practical applications.

    std::system_error Class
    The std::system_error class is a standard exception type that encapsulates an error code along with a descriptive message. This class derives from std::runtime_error and is particularly useful for throwing exceptions that represent system-level errors.

    Key features of std::system_error:

    Constructors: std::system_error can be constructed using an std::error_code or an std::error_condition, along with an optional error message.
    Accessors: Methods like code() return the std::error_code associated with the exception, providing easy access to the error details.

    ReplyDelete
  79. Thank you very much for your post, it was informative. https://www.oremconcretecompany.com

    ReplyDelete
  80. Glad to check this site. It's very informative content you shared. decorative plastering

    ReplyDelete
  81. I'm glad I found this website, very useful. denver water heater repair

    ReplyDelete
  82. Thanks for the great post! dunk tank

    ReplyDelete
  83. It makes sense that they serve different purposes based on the provided descriptions. Using create_directory as an example is a good way to illustrate the difference.


    ReplyDelete
  84. The System error support in C++0x - part 2 is the best and provides the great details on it. Also tree cutting is sometimes a problems but with the right services we can get the results that we are in need of.

    ReplyDelete
  85. Wow, this is so informative! Thank you | brick masonry

    ReplyDelete
  86. Great post! For anyone looking to escape the hustle and bustle of city life, the Best Hill Stations near Bangalore offer the perfect retreat. As a travel agency specializing in both domestic and international tour packages, we can help you plan the perfect getaway to these serene destinations. Whether it's the misty hills of Coorg, the lush greenery of Chikmagalur, or the stunning landscapes of Ooty, we have customizable packages that cater to all your travel needs. Feel free to reach out to us to make your next trip memorable and hassle-free!

    ReplyDelete
  87. Yes indeed. That's the post I really needed. It helped me a lot to get some my errors correction. on demand app development company

    ReplyDelete
  88. Just got through this amazing article post. Being a developer I learned a lot from this post and hoping for the best at upcoming post. Baby Teethers

    ReplyDelete
  89. You have a good content! Thanks for sharing painting contractors

    ReplyDelete
  90. Great post! As someone who enjoys exploring the best travel destinations, I find your insights on travel planning really helpful. If you're ever looking to escape the city for a relaxing beach getaway, you should definitely check out some amazing beach destinations near Bangalore. From serene spots like Gokarna to the lively beaches of Mangalore, there’s a lot to explore! Feel free to check out this list of the best beach places near Bangalore for some travel inspiration: Beach places near Bangalore. Safe travels!

    ReplyDelete
  91. thanks for sharing this with us
    Srinagar tours

    ReplyDelete
  92. Want to grow your online presence? Pinterest agency London
    helps connect with your audience and boost engagement.

    ReplyDelete
  93. Experiencing system errors can be frustrating, especially when they interrupt important tasks. If you’re dealing with ongoing technical issues, finding the right support can save you time and hassle. And if tech troubles are impacting your studies, it might be time to consider a more convenient solution take my class services can help you stay on track while you sort things out.

    ReplyDelete
  94. When facing technical issues during an important test, it can be frustrating. Whether it's a system error or unexpected glitch, it’s important to have reliable support. If you're dealing with technical problems during your ALEKS exam and worried about the outcome, an alternative solution is to consider professional assistance. You can avoid the stress of dealing with system errors and still get the results you need by choosing to Take My ALEKS Test for Me and let experts handle it for you.

    ReplyDelete