In C++ errno
is a preprocessor macro that is used for error indication and reporting errors that occur during a function call. It contains error codes so if a call to a function fails somehow then the errno is set to a value that corresponds to the error.
errno is defined in the header file <cerrno>
i
n C++.
Working of errno
in C++
The errno works as the explain below:
Initially at the beginning of the program, the errno
is set to zero and it changes when any error occurs.- If a function call fails it sets
errno
, then we check its value. There is no change in the value errno
if no errors occur.
Examples of errorno in C++
The following examples illustrate how we can use errno in different scenarios.
Example 1
The below example demonstrates the usage of errno for reading a file because when we try to open a file it may throw an error.
C++
// C++ program to demonstrate the use of errno for reading a
// file
#include <cerrno>
#include <cstring>
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
// Defining the filename to be opened.
const char* filename = "myfile.txt";
// Attempting to open the file using ifstream.
ifstream file(filename);
// Checking if the file was not opened successfully or
// not.
if (!file) {
// Switch case based on the error number (errno).
switch (errno) {
case ENOENT: // Case for file not existing.
cerr << "Error: File '" << filename
<< "' doesn't exist." << endl;
break;
case EACCES: // Case for access denied.
cerr << "Error: Permission denied for file '"
<< filename << "'." << endl;
break;
default: // Default case for other errors.
cerr << "Error opening file '" << filename
<< "': " << strerror(errno) << endl;
break;
}
// Return with error code 1 to indicate failure.
return 1;
}
// Closing the file if it was opened successfully.
file.close();
// Return 0 to indicate successful completion.
return 0;
}
Output
Error: File 'myfile.txt' doesn't exist.
Explanation: The above example shows how to handle error that we get when we try to open a file using ifstream
. It checks for conditions that may give error like file not existing or access being denied by using the errno
variable.
Note: Always clear errno after handling errors and use errno=0 to reset the value after handling an error.
Example 2
The below example demonstrates the use of errno to detect error in mathematical operations.
C++
// C++ program to demonstrate the use of errno to detect
// error in mathematical operations.
#include <cerrno>
#include <cmath>
#include <iostream>
using namespace std;
int main()
{
// Variable initialization with a value that will cause
// a domain error in sqrt
double x = -1.0;
// Attempt to calculate the square root of x
double result = sqrt(x);
// Check if errno is set to EDOM, indicating a domain
// error in the sqrt function
if (errno == EDOM) {
// Print an error message to stderr and return with
// error code 1
cerr << "Error: Cannot take the square root "
"of a negative number."
<< endl;
return 1;
}
// If no error, print the result
cout << "Square root of " << x << " is: " << result
<< endl;
// Return 0 indicating success
return 0;
}
Output
Error: Cannot take the square root of a negative number.
Explanation: The above example checks for EDOM after taking the mathematical values Error. When we try to calculate the square root of a negative number like (-2
), that are actually not defined and leads to a domain error.
Error Codes Associated with errorno in C++
There are lots of codes associated with errorno in C++ but some of the commonly used error codes are listed in the below table:
|
1 | EPERM | Operation not permitted |
2 | ENOENT | No such file or directory |
3 | ESRCH | No such process |
5 | EIO | I/O error |
7 | E2BIG | Argument list too long |
9 | EBADF | Bad file number |
10 | ECHILD | No child processes |
11 | EAGAIN | Try again |
12 | ENOMEM | Out of memory |
13 | EACCES | Permission denied |
Similar Reads
How to Use cin.fail() Method in C++? In C++, the cin.fail() method is a part of <iostream> library that is used to check whether the previous input operation has succeeded or not by validating the user input. In this article, we will learn how to use cin.fail() method in C++. Example: Input: Enter an integer: aOutput: Invalid Inp
2 min read
How to Read Input Until EOF in C++? In C++, EOF stands for End Of File, and reading till EOF (end of file) means reading input until it reaches the end i.e. end of file. In this article, we will discuss how to read the input till the EOF in C++. Read File Till EOF in C++The getline() function can be used to read a line in C++. We can
2 min read
How to Throw an Exception in C++? In C++, exception handling is a mechanism that allows us to handle runtime errors and exceptions are objects that represent an error that occurs during the execution of a program. In this article, we will learn how to throw an exception in C++. Throw a C++ ExceptionThrowing an exception means sendin
2 min read
How to Delete a File in C++? C++ file handling allows us to manipulate external files from our C++ program. We can create, remove, and update files using file handling. In this article, we will learn how to remove a file in C++. Delete a File in C++ To remove a file in C++, we can use the remove() function defined inside the
2 min read
How Should I Use FormatMessage() in C++? In C++, the FormatMessage() is a function used for formatting error messages returned by the system that is particularly useful for retrieving system error messages and converting them into a user-readable format. In this article, we will learn how we should use the FormatMessage function properly i
3 min read
C++ Program to Show Types of Errors In any programming language errors is common. If we miss any syntax like parenthesis or semicolon then we get syntax errors. Apart from this we also get run time errors during the execution of code. In a similar way the errors are classified as below: Syntax Errors Runtime Errors Logical Errors Link
3 min read
How to Catch All Exceptions in C++? In C++, exceptions are objects that indicate you have an error in your program. They are handled by the try-catch block in C++. In this article, we will learn how to catch all the exceptions in C++. Catching All Exceptions in C++To catch all kinds of exceptions in our catch block in C++, we can defi
2 min read
How to Catch Floating Point Errors in C++? In C++, a part of the code that may throw exceptions is enclosed in try-and-catch blocks to handle them when they arise. We can also use try...catch to catch floating point errors but it involves a bit different approach in comparison to catching standard exceptions. In this article, we will look at
2 min read
How to Throw a Custom Exception in C++? In C++, exception handling is done by throwing an exception in a try block and catching it in the catch block. We generally throw the built-in exceptions provided in the <exception> header but we can also create our own custom exceptions.In this article, we will discuss how to throw a custom e
2 min read