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.

60 comments:

Unknown said...

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?

h4tr3d said...

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.

Anonymous said...

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

Brainbox said...

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.

Melissa Falbo said...

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.

Unknown said...

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.

Gryffin said...

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/

Maria Lena said...

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

Susan said...

Celebrity net worth is a website which reports estimates of the total assets and financial activities of celebrities. Read it for more information.

Harry Adam said...

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

Harry Adam said...

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

Lorriel Sims said...

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

Isabell Kiral said...

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.

ASAP DEMO said...

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

staripl said...

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.

Office Setup said...

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.

Michaelseo said...

My spouse and i came up on your web site even though paying attention only a little submits. Wonderful technique for up coming, We are book-marking immediately use your current comprehensive soars. real estate career

UnKnown said...

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 먹튀검증

Dissertation writing services uk said...

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

Phdassistanceuk said...

Half Baked proposal dooms the project A high quality proposal is intended to satisfy others that you have a worthy thesis, and you have capability to complete it, dissertation proposal writing service, research proposal writing service, india, uk

Phdassistanceuk said...

Ph.D. Assistance is an Academic The Best Dissertation Writing Service & Consulting Support Company established in 2001. Best Dissertation Writing Services Uk, dissertation help the UK, Dissertation Help Dissertation Service Uk, Assistance & guidance for Ph.D. Tutoring and Rewriting Services – Original, Elegant and the arguments nuanced and sophisticated Establishing an Academic Tone

robertcooper said...

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.

Unknown said...

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.

Car and truck oil changes Abu Dhabi said...

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.

Ramma Foundation Repair said...

Rammafoundation is a foundation and company that can repair damage of guttersConcrete foundation repair edmonton.we provides best services for our custumers in alberta (canada)

Dim4ksan said...

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.

SOIL stabilization in houston said...

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.

performance sex honey said...

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

Tile Setting & Installation Edmonton said...

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.

Mobile Car Wash Ottawa said...

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.

Emma Jackson said...

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.

keven john said...

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.

Anonymous said...

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

Anonymous said...

Whatsapp Number Call us Now! 01537587949
It Training In Dhaka
USA pone web iphone repair USA
USA SEX WEB careful
bd sex video B tex
bd sex video sex video
bd sex video freelancing course

Anonymous said...

Thank you for the content. Stamped concrete raleigh nc

Anonymous said...

Cool stuff. Managed it services raleigh

Anonymous said...

Cool information. Locust split rail fence asheville

igoal88 said...

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

Brix said...

Thanks for sharing this great blog. ogdenbathtubrefinishing.com/

Kyzer said...

Interesting post! Great share. https://pristinewatertx.com/

logitech wireless keyboard not working said...

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

windows 12 said...

Oh what an amazing article.

متجر شوكليت الخبر said...

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!

Jennifer Garner said...

Need to take your class online? Take Your Class Online offers best online class help! Just say Take My Class Online For Me. We offer do my online class help!

Maks Romanov said...

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<

Anonymous said...

faststone capture crack
ableton live crack

Scarlette Dark said...

What is system error code?

URL: www.nashvillehoodcleaning.net

Buy chocolate gift Dammam said...

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!

Mitch said...

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

Brett said...

Awesome post! Thanks for sharing. radroofingaz.net/

Yanira Nap said...

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

Anonymous said...

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

Anonymous said...

Glad to found this nice blog. concrete companies in corpus christi

Anonymous said...

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

Anonymous said...

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

Anonymous said...

Interesting article. www.concretecoloradosprings.com 719-354-2192

Anonymous said...

Pretty nice content. www.deckscoloradosprings.net 719-259-1226

Anonymous said...

Great interesting blog. jacksonville concrete 904-440-0406

Anonymous said...

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

KashmirTravels said...

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