Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

C++ Library - <system_error>



The <system_error> header in C++ provides a way to report and handle system related errors across different platforms. It encapsulate system specific error codes into portable, easy to handle C++ objects, enabling error handling in modern applications. It decouples system errors from platform specific APIs, providing an abstraction layer that ensures consistent behaviour across different operating systems.

The <system_error> consists of two classes

  • error_code − which represents an error code associated with a particular system error. It holds both the numeric error value and the error category.
  • system_error − It is a exception class that is derived from the std::runtime_error and is used to throw exceptions that carry system related error information.

Including <system_error> Header

To include the <system_error> header in your C++ program, you can use the following syntax.

#include <system_error>

Functions of <system_error> Header

Below is list of all functions from <system_error> header.

Sr.No Functions & Description
1 assign

It assigns a another error code.

2 operator=

It assigns a error code.

3 clear

It clears the error code.

4 value

It obtains the value of the error_code.

5 category

It obtains the error_category for this error_code.

6 default_error_condition

It obtains the error_condition for this error_code.

7 message

It obtains the explanatory string for this error_code.

8 operator bool

It checks if the value is non-zero.

Non-member functions

Sr.No Functions & Description
1 operator==

It compares two error_codes.

2 operator!=

It compares two error_codes.

3 operator<

It compares two error_codes.

4 operator<=>

It compares two error_codes.

5 operator<<

It outputs the value and the category name to an output stream.

Creating Custom Error

In the following example, we are going to use the std::error_code to create a custom error code.

#include <iostream>
#include <system_error>
int main() {
   std::error_code x(1007, std::generic_category());
   std::cout << "Error code: " << x.value() << "\n";
   std::cout << "Error message: " << x.message() << "\n";
   return 0;
}

Output

Output of the above code is as follows −

Error code: 1007
Error message: Operation not permitted

Handling System Errors

Consider the following example, where we are going to throw a std::system_error exception with an error code indicating a permission denied error.

#include <iostream>
#include <system_error>
int main() {
   try {
      throw std::system_error(std::make_error_code(std::errc::permission_denied));
   } catch (const std::system_error & x) {
      std::cout << "Caught error: " << x.what() << "\n";
      std::cout << "Error code: " << x.code() << "\n";
   }
   return 0;
}

Output

Following is the output of the above code −

Caught error: Permission denied
Error code: generic:13
Advertisements