cerr in C++

Overview
The cerr in C++ is a standard output stream for errors. This object is declared in the <iostream> header file. It is basically used to print some information or error on the console.
What is cerr in C++?
The cerr is an object of class ostream, which is associated with the standard error output stream. It is used along with insertion operator(<<) to print the error and information on the console. Also, cerr is an unbuffered stream i.e. it prints the information to the console directly without storing it in buffer. The flush function is called every time before the print operation. To use the cerr in our program we need to import the iostream header file. In the cerr, here 'c' represents character.
Transform Your Career
Choose from our industry-leading programs designed for career success
Modern Software and AI Engineering Program
Master full-stack development with AI integration
+1000 moreModern Data Science and ML with specialisation in AI
Advanced data science techniques with AI specialization
+1000 moreAdvanced AIML with Specialisation in Agentic AI
Deep dive into AIML with focus on Agentic systems
+1000 moreDevOps, Cloud & AI Platform Engineering
Build and manage AI-powered cloud infrastructure
+1000 moreAI Engineering Advanced Certification by IIT-Roorkee
Premier AI engineering certification from IIT-Roorkee
Syntax of cerr in C++
The syntax of cerr is pretty simple. It is quite similar to the syntax of cout object.
Example
Output:
More Examples
Opening a File
Output:
Explanation:
- In this case, the sample.txt file doesn't exist. So, else block is being executed which is printing some error string on the console.
Try Catch
Output:
Explanation:
- Initially, we have defined an array and we are finding the size of that array.
- In the try block, we have defined a condition to throw an error whenever the index is out of range.
- In the catch block, we are catching the error and cerr is being used to print the error.
Conclusion
- cerr is an object of ostream class.
- It is declared in iostream header file.
- It is used to print the information or error to the console.
Scaler Placement Report and Statistics
Scaler learners achieved 2.5x salary growth with average post-Scaler CTC reaching ₹23L.