Home C++ cerr tutorial in C++ with code examples

cerr tutorial in C++ with code examples

In C++, cerr is an object of the ostream class used to output error messages to the standard error stream.

The cerr stream is typically unbuffered, meaning that messages are displayed immediately without waiting for a newline or flush.

This makes it useful for error reporting and debugging since error messages are shown as soon as they are generated, regardless of what’s happening with the standard output.

Key Points About cerr

  1. Unbuffered Output: cerr doesn’t wait for the buffer to fill up; it outputs immediately, making it ideal for error messages.
  2. No Buffering Overhead: Error messages are sent directly to the output without delay.
  3. Used for Error Reporting: Useful for displaying error messages without mixing them with regular program output.

Basic Syntax of cerr

cerr << expression;
  • The << operator (insertion operator) is used to send output to cerr.
  • cerr does not require flushing like cout << endl; because it’s unbuffered by default.

1. Basic cerr Usage for Error Messages

A simple example using cerr to display an error message.

#include <iostream>
using namespace std;

int main() {
    cerr << "Error: Unable to open file." << endl;
    return 0;
}

Explanation:

  • cerr << “Error: Unable to open file.” << endl; displays an error message immediately.
  • endl flushes the stream, but it’s not necessary for cerr because it’s unbuffered.

Output:

Error: Unable to open file.

2. Using cerr in Conditional Statements

cerr can be used to report specific errors based on conditions, such as invalid input.

#include <iostream>
using namespace std;

int main() {
    int number;
    cout << "Enter a positive number: ";
    cin >> number;

    if (number < 0) {
        cerr << "Error: Negative numbers are not allowed." << endl;
    } else {
        cout << "You entered: " << number << endl;
    }

    return 0;
}

Explanation:

  • If the user enters a negative number, cerr outputs an error message.
  • cerr is used here to notify the user immediately if an invalid input is given.

Sample Output:

Enter a positive number: -5
Error: Negative numbers are not allowed.

3. Displaying Error Messages in Loops with cerr

cerr can be used within loops to report multiple errors.

#include <iostream>
using namespace std;

int main() {
    int numbers[5];
    cout << "Enter 5 positive integers:" << endl;

    for (int i = 0; i < 5; i++) {
        cin >> numbers[i];
        if (numbers[i] < 0) {
            cerr << "Error: " << numbers[i] << " is not a positive integer." << endl;
        }
    }

    cout << "Processing complete." << endl;
    return 0;
}

Explanation:

  • cerr outputs an error message each time a negative number is entered.
  • Using cerr in a loop is helpful when multiple inputs need to be validated.

Sample Output:

Enter 5 positive integers:
-3
Error: -3 is not a positive integer.
5
7
-1
Error: -1 is not a positive integer.
8
2
Processing complete.

4. Using cerr with File Handling Errors

cerr is commonly used to report file-handling errors, like when a file cannot be opened.

#include <iostream>
#include <fstream>
using namespace std;

int main() {
    ifstream file("nonexistent.txt");

    if (!file) {
        cerr << "Error: Could not open file 'nonexistent.txt'." << endl;
    } else {
        cout << "File opened successfully." << endl;
    }

    return 0;
}

Explanation:

  • cerr is used to notify the user that the file couldn’t be opened.
  • It outputs an error message immediately without waiting for any buffer.

Output:

Error: Could not open file 'nonexistent.txt'.

5. Using cerr to Report Division by Zero Errors

A common error is division by zero, which can be detected and reported with cerr.

#include <iostream>
using namespace std;

int main() {
    double numerator, denominator;

    cout << "Enter numerator: ";
    cin >> numerator;

    cout << "Enter denominator: ";
    cin >> denominator;

    if (denominator == 0) {
        cerr << "Error: Division by zero is not allowed." << endl;
    } else {
        cout << "Result: " << (numerator / denominator) << endl;
    }

    return 0;
}

Explanation:

  • If denominator is 0, cerr outputs an error message instead of performing the division.

Sample Output:

Enter numerator: 10
Enter denominator: 0
Error: Division by zero is not allowed.

6. Using cerr in Exception Handling

cerr can be used in conjunction with exception handling to display error messages when exceptions are caught.

#include <iostream>
#include <stdexcept>
using namespace std;

int main() {
    try {
        throw runtime_error("Runtime error occurred.");
    } catch (const runtime_error& e) {
        cerr << "Caught exception: " << e.what() << endl;
    }

    return 0;
}

Explanation:

  • A runtime_error exception is thrown, and when caught, cerr displays the error message.
  • Using cerr in exception handling is useful for debugging or logging errors.

Output:

Caught exception: Runtime error occurred.

7. Using cerr for Debugging Purposes

You can use cerr statements to debug code by displaying variable values or function calls during execution.

#include <iostream>
using namespace std;

int factorial(int n) {
    if (n < 0) {
        cerr << "Error: Factorial of negative number " << n << " is not defined." << endl;
        return -1;
    }

    int result = 1;
    for (int i = 1; i <= n; i++) {
        result *= i;
        cerr << "Intermediate factorial at i = " << i << ": " << result << endl;
    }
    return result;
}

int main() {
    int num;
    cout << "Enter a positive integer: ";
    cin >> num;

    int result = factorial(num);
    if (result != -1) {
        cout << "Factorial: " << result << endl;
    }

    return 0;
}

Explanation:

  • cerr is used in the factorial function to display intermediate results for debugging.
  • If n is negative, cerr outputs an error message, and the function returns -1.

Sample Output:

Enter a positive integer: 5
Intermediate factorial at i = 1: 1
Intermediate factorial at i = 2: 2
Intermediate factorial at i = 3: 6
Intermediate factorial at i = 4: 24
Intermediate factorial at i = 5: 120
Factorial: 120

8. Using cerr with boolalpha for Boolean Debugging Information

For debugging boolean expressions, boolalpha displays true or false values instead of 1 and 0.

#include <iostream>
using namespace std;

int main() {
    bool isAdmin = false;

    cerr << "Debug: User is admin: " << boolalpha << isAdmin << endl;

    if (!isAdmin) {
        cerr << "Error: Access denied. User is not an admin." << endl;
    }

    return 0;
}

Explanation:

  • boolalpha displays isAdmin as true or false instead of 1 or 0.
  • Using cerr with boolalpha makes debugging boolean values clearer.

Output:

Debug: User is admin: false
Error: Access denied. User is not an admin.

9. Using cerr in a Function to Handle Errors

You can define a function that uses cerr to report specific errors and call it as needed.

#include <iostream>
using namespace std;

void showError(const string& errorMsg) {
    cerr << "Error: " << errorMsg << endl;
}

int main() {
    int age;
    cout << "Enter your age: ";
    cin >> age;

    if (age < 0) {
        showError("Age cannot be negative.");
    } else {
        cout << "Age entered: " << age << endl;
    }

    return 0;
}

Explanation:

  • The showError function uses cerr to display a custom error message.
  • This approach allows for centralized error handling in functions.

Sample Output:

Enter your age: -5
Error: Age cannot be negative.

10. Using cerr to Log Warnings

cerr can also be used to display warning messages, which may not be fatal but indicate a potential issue.

#include <iostream>
using namespace std;

int main() {
    int score;
    cout << "Enter your score: ";
   

 cin >> score;

    if (score < 0 || score > 100) {
        cerr << "Warning: Score out of typical range (0-100)." << endl;
    }

    cout << "Score entered: " << score << endl;
    return 0;
}

Explanation:

  • cerr displays a warning if the entered score is outside the normal range of 0 to 100.
  • Warnings do not stop the program but alert the user to potential issues.

Sample Output:

Enter your score: 110
Warning: Score out of typical range (0-100).
Score entered: 110

Summary Table of cerr Use Cases

Use Case Code Example Description
Basic Error Message cerr << “Error: …” << endl; Displays an error message
Conditional Error Message if (error) cerr << “Error…”; Displays errors based on conditions
Error Messages in Loops cerr in a loop to display multiple errors Reports errors for each invalid input
File Handling Errors if (!file) cerr << “File error”; Reports errors when a file cannot be opened
Division by Zero if (den == 0) cerr << “Division error”; Reports division by zero errors
Exception Handling cerr << e.what(); in catch block Displays error message when exception is caught
Debugging with Intermediate Output cerr << “Debug value: ” << value; Outputs variable values or steps for debugging
Boolean Debugging with boolalpha cerr << boolalpha << isAdmin; Displays true or false instead of 1 or 0
Centralized Error Reporting showError(“Error msg”); Uses a function for standardized error reporting
Warning Messages cerr << “Warning: …”; Outputs warning messages for non-fatal issues

Complete Example: Centralized Error Reporting and Logging with cerr

This example combines various cerr use cases, including warnings, conditional errors, and centralized error handling in a single program.

#include <iostream>
#include <fstream>
using namespace std;

void logError(const string& message) {
    cerr << "Error: " << message << endl;
}

void logWarning(const string& message) {
    cerr << "Warning: " << message << endl;
}

int main() {
    int age;
    double salary;
    ifstream file("data.txt");

    if (!file) {
        logError("Unable to open data file.");
    }

    cout << "Enter your age: ";
    cin >> age;
    if (age < 0) {
        logError("Age cannot be negative.");
    }

    cout << "Enter your salary: ";
    cin >> salary;
    if (salary < 0) {
        logWarning("Salary cannot be negative. Setting to 0.");
        salary = 0;
    }

    cout << "Age: " << age << ", Salary: " << salary << endl;
    return 0;
}

Sample Output:

Error: Unable to open data file.
Enter your age: -5
Error: Age cannot be negative.
Enter your salary: -2000
Warning: Salary cannot be negative. Setting to 0.
Age: -5, Salary: 0

Key Takeaways

  • cerr is used to output error messages immediately to the standard error stream.
  • Being unbuffered, cerr is ideal for debugging and error reporting where immediate feedback is required.
  • Centralizing error handling with functions or using cerr conditionally enhances readability and consistency in error reporting.

You may also like