Wednesday, April 14, 2010

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

[ part 1, part 2, part 3, part 4 ]

Creating your own error conditions

User-extensibility in the <system_error> facility is not limited to error codes: error_condition permits the same customisation.

Why create custom error conditions?

To answer this question, let's revisit the distinction between error_code and error_condition:

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

This suggests some use cases for custom error conditions:

  • Abstraction of OS-specific errors.

    Let's say you're writing a portable wrapper around getaddrinfo(). Two interesting error conditions are the tentative "the name does not resolve at this time, try again later", and the authoritative "the name does not resolve". The getaddrinfo() function reports these errors as follows:

    • On POSIX platforms, the errors are EAI_AGAIN and EAI_NONAME, respectively. The error values are in a distinct "namespace" to errno values. This means you will have to implement a new error_category to capture the errors.
    • On Windows, the errors are WSAEAI_AGAIN and WSAEAI_NONAME. Although the names are similar to the POSIX errors, they share the GetLastError "namespace". Consequently, you may want to reuse std::system_category() to capture and represent getaddrinfo() errors on this platform.

    To avoid discarding information, you want to preserve the original OS-specific error code while providing two error conditions (called name_not_found_try_again and name_not_found, say) that API users can test against.

  • Giving context-specific meaning to generic error codes.

    Most POSIX system calls use errno to report errors. Rather than define new errors for each function, the same errors are reused and you may have to look at the corresponding man page to determine the meaning. If you implement your own abstractions on top of these system calls, this context is lost to the user.

    For example, say you want to implement a simple database where each entry is stored in a separate flat file. When you try to read an entry, the database calls open() to access the file. This function sets errno to ENOENT if the file does not exist.

    As the database's storage mechanism is abstracted from the user, it could be surprising to ask them to test for no_such_file_or_directory. Instead, you can create your own context-specific error condition, no_such_entry, which is equivalent to ENOENT.

  • Testing for a set of related errors.

    As your codebase grows, you might find the same set of errors are checked again and again. Perhaps you need to respond to low system resources:

    • not_enough_memory
    • resource_unavailable_try_again
    • too_many_files_open
    • too_many_files_open_in_system
    • ...

    in several places, but the subsequent action differs at each point of use. This shows that there is a more general condition, "the system resources are low", that you want to test for and react to in your code.

    A custom error condition, low_system_resources, can be defined so that its equivalence is based on a combination of other error conditions. This allows you to write each test as:

    if (ec == low_system_resources)

    and so eliminate the repetition of individual tests.

The definition of custom error conditions is similar to the method for error_codes, as you will see in the steps below.

Step 1: define the error values

You need to create an enum for the error values, similar to std::errc:

enum class api_error
low_system_resources = 1,

The actual values you use are not important, but you must ensure that they are distinct and non-zero.

Step 2: define an error_category class

An error_condition object consists of both an error value and a category. To create a new category, you must derive a class from error_category:

class api_category_impl
: public std::error_category
virtual const char* name() const;
virtual std::string message(int ev) const;
virtual bool equivalent(
const std::error_code& code,
int condition) const;

Step 3: give the category a human-readable name

The error_category::name() virtual function must return a string identifying the category:

const char* api_category_impl::name() const
return "api";

Step 4: convert error conditions to strings

The error_category::message() function converts an error value into a string that describes the error:

std::string api_category_impl::message(int ev) const
switch (ev)
case api_error::low_system_resources:
return "Low system resources";

However, depending on your use case, it may be unlikely that you'll ever call error_condition::message(). In that case, you can take a shortcut and simply write:

std::string api_category_impl::message(int ev) const
return "api error";

Step 5: implement error equivalence

The error_category::equivalent() virtual function is used to define equivalence between error codes and conditions. In fact, there are two overloads of the error_category::equivalent() function. The first:

virtual bool equivalent(int code,
const error_condition& condition) const;

is used to establish equivalence between error_codes in the current category with arbitrary error_conditions. The second overload:

virtual bool equivalent(
const error_code& code,
int condition) const;

defines equivalence between error_conditions in the current category with error_codes from any category. Since you are creating custom error conditions, it is the second overload that you must override.

Defining equivalence is simple: return true if you want an error_code to be equivalent to your condition, otherwise return false.

If your intent is to abstract OS-specific errors, you might implement error_category::equivalent() like this:

bool api_category_impl::equivalent(
const std::error_code& code,
int condition) const
switch (condition)
case api_error::name_not_found:
#if defined(_WIN32)
return code == std::error_code(
WSAEAI_NONAME, system_category());
return code = std::error_code(
EAI_NONAME, getaddrinfo_category());
return false;

(Obviously getaddrinfo_category() needs to be defined somewhere too.)

The tests can be as complex as you like, and can even reuse other error_condition constants. You may want to do this if you're creating a context-specific error condition, or testing for a set of related errors:

bool api_category_impl::equivalent(
const std::error_code& code,
int condition) const
switch (condition)
case api_error::low_system_resources:
return code == std::errc::not_enough_memory
|| code == std::errc::resource_unavailable_try_again
|| code == std::errc::too_many_files_open
|| code == std::errc::too_many_files_open_in_system;
case api_error::no_such_entry:
return code == std::errc::no_such_file_or_directory;
return false;

Step 6: uniquely identify the category

You should provide a function to return a reference to a category object:

const std::error_category& api_category();

such that it always returns a reference to the same object. As with custom error codes, you can use a global:

api_category_impl api_category_instance;

const std::error_category& api_category()
return api_category_instance;

or you can make use of C++0x's thread-safe static variables:

const std::error_category& api_category()
static api_category_impl instance;
return instance;

Step 7: construct an error_condition from the enum

The <system_error> implementation requires a function called make_error_condition() to associate an error value with a category:

std::error_condition make_error_condition(api_error e)
return std::error_condition(

For completeness, you should also provide the equivalent function for construction of an error_code. I'll leave that as an exercise for the reader.

Step 8: register for implicit conversion to error_condition

Finally, for the api_error enumerators to be usable as error_condition constants, enable the conversion constructor using the is_error_condition_enum type trait:

namespace std
template <>
struct is_error_condition_enum<api_error>
: public true_type {};

Using the error conditions

The api_error enumerators can now be used as error_condition constants, just as you may use those defined in std::errc:

std::error_code ec;
load_resource("http://some/url", ec);
if (ec == api_error::low_system_resources)

As I've said several times before, the original error code is retained and no information is lost. It doesn't matter whether that error code came from the operating system or from an HTTP library with its own error category. Your custom error conditions can work equally well with either.

Next, in what will probably be the final instalment, I'll discuss how to design APIs that use the <system_error> facility.


«Oldest   ‹Older   401 – 500 of 500
AFREEN said...

The maker of TurboTax, one of the companies that has promised the IRS to offer free tax filing to low-income earners.for more visit our websit

AFREEN said...

TurboTax has excellent customer service options. You can connect with a customer service representative by phone, email or chat as well as with this link

AFREEN said...

TurboTax is a software package for preparing US income tax returns produced by Intuit. Click on this link to know about it.

Anonymous said...

faststone capture crack
ableton live crack said...

This is a great tip especially to those fresh to the blogosphere. Brief but very accurate info… Thank you for sharing this one. A must read post! said... is also known as Netgear Orbi Login helps users access broken web connections every moment of each device said...

ORBILOGIN.COM is a one stop platform for all your e-hospital needs, the site is developed to provide a complete and hassle free online registration and booking experience. With, you can register for, schedule, and pay all your medical tests, scans, and visits to a medical center from one screen. ORBILOGIN.COM is the only E-Health Portal that supports both the desktop and mobile platform. said...

Need something better to increase your internet speed? You don't have to worry anymore. Netgear offers you the most powerful Orbi router with several advanced features. This will allow you to easily do the Netgear Orbi login without any hassle. It has high security and parental control which makes browsing safe for your kids. Here you can find more detailed information, such as how to access or You can also learn the setup process with like the Orbi app. You can then troubleshoot using the troubleshooting steps and update the router's firmware. said...

It’s really a great and helpful piece of info.
I am happy that you just shared this helpful information with us. said...

We stumbled over here from a different page and thought I might as well check things out. I like what I see so now i am following you.

Netgear Router Login said...

If you want to access the Netgear Router then open the browser & type & enter fill all the details & select the login button.

Nighthawk router login said...

I like the valuable information you provide in your
Articles. I will bookmark your weblog and check again here frequently. said...

NETGEAR router login using the default login details. When the Login panel appears, it will require user data, ie. username and password. said...

I’m quite sure I will learn plenty of new
stuff right here! Best of luck for the next! said...

Hi there Dear, are you genuinely visiting
this website on a regular basis, if so then you will absolutely
get good know-how. said...

For Nighthawk router setup, Connect the device to the router's Wifi network. Your network name and password are shown on the screen Login said...

Fine with your permission let me to take hold of your RSS feed to keep up to date with imminent post. Thank you a million and please keep up the Rewarding work. said...

Thank you for sharing excellent information. Your site is very cool.

NDTV TODAY said...

business news in hindi

marisa said...

Ufabet is an excellent option to start. There are great rewards and customer service 24/7. Play on your phone! UFABET also offers a bonus scheme which is attractive.

Anonymous said...

ignou mba project
ignou mttm project
ignou mba project said...

ignou bts project
ignou assignment
ignou study material
ignou mapc project

blogger said...

Thanks For Sharing Health News In Hindi
Thanks For Sharing Lifestyle News In Hindi
Thanks For Sharing Crime News In Hindi
Thanks For Sharing Breaking News In Hindi

Ahaana jain said...

Fantastic piece, well tailored…. You sort of cleared my phobias… Now I can give it a shot… I pray I don’t run out of contents!…a big kudos

Future Of E-commerce In 2021
Keyword Research Strategy said...

I read this article completely regarding the resemblance of most up-to-date and earlier technologies, it’s amazing article. said...

These are in fact fantastic ideas in about blogging. You have touched some good factors here. Any way keeps up writing.

orbi firmware update failed said...

I am truly delighted to read this web site posts which includes tons of valuable data, thanks for providing such information.
orbi firmware update failed

routerloginnet said...

It’s really a great and helpful piece of information

routerlogin said...

I like the valuable information you provide in your. articles. I will bookmark your weblog and check again here frequently. said...

I will be grateful if you continue this in future.Many people will be benefited from your writing.Cheers!

routerloginnet said...

I will be grateful if you continue this in future. Many people will be benefited from your writing.Cheers! said...

I will be grateful if you continue this in future.Many people will be benefited from your writing. Cheers! Setup said...

Wow, awesome blog layout! How long have you been blogging for? said...

Hi there dear, are you genuinely visiting. This website on a regular basis, if so then you will absolutely said...

I’m really impressed with your writing skills as well as with the layout on your weblog

Ahaana jain said...

Hi! I really like your content. Your post is really informative.

Customised Software
Custom Software Application Development India

Ahaana jain said...

I had no idea what a blog was or how to start one

Software Development Agency
Top Software Development Companies

Ahaana jain said...

Thanks for providing such a great article, this article is very helpful for me, a lot of thanks sir

Top Web Development Companies In India
Best Web Developing Companies

Ahaana jain said...

Fantastic piece, well tailored…. You sort of cleared my phobias… Now I can give it a shot… I pray I don’t run out of contents!…a big kudos

Custom Application Development Company
Software Development Firm

Anonymous said...

Asynchronous functions are often found in front-end applications and used particularly in independent, high-volume, IO tasks.

Know more about stamped concrete cracking

Stamped Concrete Frederick MD said...

The main distinction between synchronous and asynchronous communication is that synchronous communications involve pre-arranged, in-person, audio, or video exchanges.

Stamped Concrete Frederick MD is serving quality concrete service locally.

HVAC Heating Spokane said...

As its name suggests, C++ async is a function template fn that runs callbacks or functions or function objects asynchronously by accepting them as arguments.

Also guys you can check our HVAC Heating Spokane

Concrete Patio Harrisonburg said...

Excellent information on your site, thanks for the platform to allow us to make comments.

Concrete Patio Harrisonburg is the best concrete patio provider in town!

Spokane Countertops said...

The content is really nice, it is well written.

By the way guys you can also visit our best Spokane Countertops

Ahaana jain said...

I will definitely use this information in the very near future. I have saved this link and will return in a
How To Make An App Like Tinder
How Video Marketing Grow Your Business

Ahaana jain said...

This was a fantastic blog. A lot of very good information given,

Web Design Company Toronto
Website Design Company

Beautyglaming said...

Thanks For Sharing Elf Bar
Thanks For Sharing vaperdudes

Travis john said...

Accessing the web address can help you gain access to the device settings easily. This blog will effectively help users read through the process. Appreciate the post.

Jennaforbes said...

Amped wireless devices can be managed using This blog accurately explains the process and can help users understand it in easy words. Really liked the layout. Please keep posting.

Ahaana jain said...

This was a fantastic blog. A lot of very good information given,

Best Digital Marketing Company
Top Digital Marketing Companies In 2021

Yulanda Youngstrom said...

The closest private tutoring service pertains to mom's house - quality & selected private tutors in Jabodetabek ... for more information

Ahaana jain said...

Thanks for providing such a great article, this article is very helpful for me, a lot of thanks sir

Keyword Research Strategy
Learn Graphic Designing

Beautyglaming said...

Thanks For Sharing Techradiance

Jeannette Elhosni said...

For those of you which sign-up your youngster, alongside the finest educators, this site offers tutoring and personal teaching expert services inside Jabodetabek ... go to for further

Bunny .cow said...

โปรโมชั่นทีเด็ดที่สายปั่นไม่ควรพลาด ต้อง SAGAME โปร โม ชั่ น บาคาร่าสุดคุ้ม แจกเครดิตและโบนัสฟรีแบบชุดใหญ่จัดเต็ม และมีโปรโมชั่นที่แจกค่าคอมมิชชั่นแบบงาม ๆ ไม่ว่าจะเป็น โปรโมชั่นคืนค่าคอมมิชชั่น 0.3% ฟรีทุกยอดแทง หรือ โปรโมชั่นแนะนำเพื่อนรับค่าคอมมิชชั่น 0.5% ฟรี บอกเลยว่าโปรนี้ยิ่งชวนยิ่งรวย ได้ทั้งเพื่อนเดิมพัน ได้ทั้งค่าคอมมิชชั่น แบบนี้คือว่าคุ้มสุด ๆ และมีสิทธิประโยชน์ดี ๆ ให้เลือกรับอีกมากมาย รับรองไม่มีผู้เล่นคนไหนจะต้องกลับบ้านมือเปล่าอย่างแน่นอน และแจ็คพ็อตแตกง่าย โบนัสแตกไวที่สุด สำหรับสมาชิกใหม่ที่สมัครสมาชิกกับเราวันนี้รับเครดิตบาคาร่าฟรีทันทีสูงสุดถึง 100%

30 Days Dubai Visa said...

The complete global wants to visit Dubai because of its high-upward thrust homes, beautiful seashores, and warm, welcoming humans. The us of a is well-known for its business centers and popular visitor locations. If you need to go to Dubai or deliver a loved one, you need to attain a Dubai tourist visa.

zlibrary said...

Zlibrary has thousands of PDF copies of books, papers, and journals that have been published. It was once known as BookFinder. A virtual library called Z-lib or Zlibrary has a database of scholarly, general interest, and academic books and journals.

kamenrider said...

บาคาร่าเว็บตรง บาคาร่าออนไลน์ที่ดีที่สุดที่เหล่านักพนันไว้วางใจและยกให้เป็นคาสิโนที่ได้มาตรฐานที่สุด เว็บตรง ไม่ผ่านเอเย่นต์ การเงินปลอดภัย 100% ท่านสามารถเล่น บาคาร่า ด้วยระบบอัตโนมัติ ผ่านทางหน้าเว็บไซต์ได้จากทุกช่องทาง อยู่ที่ไหนก็สามารถเล่นได้

data science and machine learning said...

Thanks for providing such a great article...keep posting
pls suggest good article regarding data science and machine learningdata science and machine learning

Harry mason said...

Very Interesting article. Thank you for sharing with us.
Necc egg rate today
Barwala egg rate today
Hyderabad egg rate today
Kolkata egg rate today
ajmer egg rate today
namakkal egg rate today
mumbai egg rate today

Lorretta Finster said...

Do you want tutoring services or private lessons within the Greater Jakarta area and its surroundings? Do you need private tutoring services... click for more information

Clark said...

Your blog brings me a great deal of fun. Good luck with the site.
exercise equipment junk removal west palm beach fl

Vipin Kumar said...

Dayitwa Education is committed to providing the necessary Online learning Education to reach the highest platform.
This institute offers a variety of courses for both undergraduate and postgraduate students. This distance learning center in Satya Niketan is accredited by Many Universities and regulated by the same rules as the other constituent colleges. Correspondence education is an excellent option for those who are unable to attend regular classes. During this type of study, you receive course materials by post and return them to the authority for evaluation. There are a number of distinguished institutes in Delhi that provide correspondence education.
Correspondence colleges in Delhi offer a convenient option for completing your education without interrupting your regular job.

Nikhil Pandey said...

If you are looking for the best Stock Market Trading Course in India, then Skillshiksha is the right place for you. It provides the best stock trading training to newbies, who are eagerly looking to learn about trading stocks. The training offered by this institute is designed according to the current needs of market traders. Skillshiksha is the best stock market guru in India who offers the top-class course on the Indian Stock Market. The course is also approved by NSE and ICICI bank and is offered at an affordable price so that anyone can afford it.
Skillshiksha provides you with the best Stock Market Training Programme in India. We have a team of professionals who make sure that you get to learn everything that you need to know about Trading on the market. Are you looking for an easy way to make money? Skillshiksha is the solution. The leading Stock Market Trading Career Training Institute in India. It offers Stock Market Courses that are designed by industry experts and faculty who have more than 25 years of experience in this industry. Skillshiksha provides educational services to those who want to make a career out of investing in stocks and shares.
I bet you know that skillshiksha is the best Stock Market Trading Course in India. If yes, then let me tell you more about this course to give you a chance to learn how to make money by trading. And you will surely become a millionaire. We are sure that you have seen a shocking rise in Stock Market Costs. The stock market is getting more and more expensive, but now, these days there are many training courses to help you with your job. Some courses can be expensive because they cost up to a lakh or even more, but SkillShiksha is offering a wonderful course that offers you the best facility and training at a very affordable cost.
If you want to learn the stock market, or if you are already into it, then skillShiksha is the right place for your stock market learning. You may have heard about skillShiksha in other places, but here I will explain how and why this one is different from others.

Clark said...

Your blog brings me a great deal of fun. Good luck with the site.
lean six sigma california

shagun said...

Online Strikers is thedigital marketing. This is best digital marketing agency has been giving useful promoting administrations to organizations of different kinds for the last numerous years. other digital marketing in Delhi that self-announce themselves to be the Best digital marketing agency in Delhi. We are the Best digital marketing agency in Delhi in light of the effective work we had with our clients and the criticism we have gotten from them. Online Strikers is maybe the Advanced Showcasing Office in Delhi that doesn't settle just on its web or web based advertising administrations. We the group at Online Strikers go each mile and past to assist our clients with winning customary clients through viable promoting methodologies and to get that done, we likewise offer disconnected showcasing administrations. Because of our conviction that clients are all over, at each stage and at each stage, we don't believe our clients should lose even any single one of them, online strikers offer all types of digital marketing services like seo services, web development, smo services cpm , etc. to our clients more customers. The way we deal with each client's record proficiently is one reason. We offer a complete package of all the things mentioned above at only the cost of the service, no matter what service you choose to take.

Rithik Prakash said...

Discover Our Top-Ranked MBA Program – MBA Distance Education
A Distance MBA is an online-based MBA program. MBA Distance Education course is designed in such a way that no need to attend classes at the college campus. We offer a comprehensive array of distance learning programs such as; MBA, law, and many more at discount prices. Because you’ll be able to take your courses online, you’ll be able to earn your degree while working at your current job.
Dayitwa Education provides the facility of Post Graduate Courses in Distance Education. Through this, you can get an academic qualification by studying part-time. You can get a valuable education without sacrificing your time for work or family commitments. If you're ready to take your career to the next level, a bachelor's degree in business may be all you need. But with so many options out there, it can be tough to find the right program. That's where we come in!
At Dayitwa Education, we offer an online MBA degree that will help you advance your career. Our MBA distance education program offers a degree from one of India's top-ranked universities, along with an on-campus interview and personalized guidance from our team of experts. You'll be able to earn your degree while working remotely, so you can focus on growing your business instead of taking time off work.
Dayitwa Education is here to educate you.
We are a leading online MBA distance education provider in India. We offer accredited courses and degrees from top-ranked universities in India, at an affordable price. If you're looking for an MBA degree, we will help you find the best university that fits your needs and budget.
If you're ready to apply, visit our homepage today!
We connect you with the best accredited MBA colleges and universities in India through our partner network. Apply today!

Clark said...

I have never heard of this information before. Thank you so much for sharing!
property clean outs boca raton

Clark said...

I have never heard of this information before. Thank you so much for sharing!
storage unit clean outs palm springs fl

bharanidevi said...

Excellent post. Thank you for sharing with us.
Thirumana porutham
Rasi Natchathiram
Numerology Calculator in Tamil

Clark said...

This post truly made my day. thanks!
business junk removal delray beach

Clark said...

This post truly made my day. You can not imagine simply how much time I had spent for this info! Thanks!

lkjhgfd said...

my problem with exceptions is less about performance and more about being very anxious of a random exception from a random function that I didn't think can throw exceptions.

Clark said...

Your blog brings me a great deal of fun. Good luck with the site.
hardscapes greensboro nc

Clark said...

Thanks for sharing this information. Good luck with the site.
retaining walls jupiter

Clark said...

Thanks for sharing this information. Good luck with the site.
hardscapes jupiter

Clark said...

Your blog brings me a great deal of fun. Good luck with the site.
landscape lighting wellington fl

Clark said...

Good luck with the site.
retaining walls west palm beach

Anonymous said...

very beneficial information shared in this text, perfect written! . ทางเข้าjoker

Clark said...

Good luck with the site.
custom pools wellington fl

clare said...

BUSINESS FOR SALE a business is hard, but it doesn't have to be impossible. At ProfitJunction we believe that anyone can start and succeed in business—provided they put in the hard work. We have the resources and expertise to help you get started and grow your business. We have products and services to suit every budget and need, from local marketing through SEO
services to branding and product development. Our team of experienced professionals can help
get your business off the ground quickly and keep it running smoothly from there. So if you're looking for a company that has your best interests at heart, ProfitJunction is the resource you need.

Clark said...

Good luck with the site.
modern pools jupiter

Clark said...

Thanks for sharing this information. Good luck with the site.
dallas retaining walls

Clark said...

Thanks for sharing this information. Good luck with the site.
we buy houses allentown pa

Clark said...

Thanks for sharing this information. Good luck with the site.
sell a term life insurance policy

Clark said...

Thanks for sharing this information. Good luck with the site.

Clark said...

Very interesting to read this article. I would like to thank you for the efforts
tree trimming arlington tx

Qita said...

PFTP (Pakistan Freelancing Training Program) is designed for Pakistan’s freelancing industry. Freelancing is growing rapidly, with more and more and Pakistanis are getting success as freelancers. So, there are a number of reasons for this growth, including the increasing availability of internet access and the growing popularity of online work platforms.

Harrisonburg Emergency Tree Service said...

Thank you for this wonderful information looking forward to more. I really appreciate your efforts to write such an amazing piece of content for us.

Check out the Harrisonburg Emergency Tree Service

אטרקציות לבר מצווה said...

I loved your amazing blog, I read a lot of material that helped me a lot, thank you very much

שרון כהן said...
This comment has been removed by the author.
שרון כהן said...

אתר שלי

Stamped Concrete Tri-Cities said...

Excellent blog here! It’s an incredible posting with verified and truly helpful information.

Check out now the Stamped Concrete Tri-Cities

Clark said...

Thanks for sharing this information. Good luck with the site.
wauwatosa cash house buyer

Fullstack said...

We find your site to be really informative, and we'd love to see more of your writings in the near future.


So lucky to come across your excellent blog. Your blog brings me a great deal of fun. Good luck with the site.
go java burn

James said...

I liked most of the writers intent.

James said...

I liked most of the writers intent.

baltimore house buyers

dipanshu sharma said...

Find the best real estate lawyers in Brampton, Cambridge, Kitchener & Ontario for expert legal representation during your home buying/selling process. Real Estate Lawyer in Brampton


Discover the Best Smart Accessories at Saver Accessories - Shop Now and Save on the Latest Tech Gear! Browse our Selection and Upgrade Your Life Today Order Now:0306 9076607
Best Smart Accessories

«Oldest ‹Older   401 – 500 of 500   Newer› Newest»