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