C++

Cerr C++ Examples

When we have to work with C++ programming, we may have different situations when we have to face errors. So, to display that error, we utilize the “cerr” keyword in C++. We can say that we utilize the “cerr” object to print the error message in C++. The “iostream” header file contains the declaration of this object. It is utilized with the “<<” insertion symbols to display the error or detail that we entered in the console. We will learn this “cerr” object thoroughly in this guide.

Example 1:

The “iostream” is the included header file here which we placed so that we may utilize the “cin” or “cout” methods in our code as both methods are declared inside it. The “cerr” object is also declared in this header file. Then, we have the “std namespace”. Now, we don’t need to add this “std” with each function independently.

Then, “main()” is invoked here. Below this, we utilize the “cerr” object and place the error message that we want to display on the console. We type the “An Error occurred here!” message in this “cerr” after placing the insertion symbols. When we run this program, the given message is displayed without using the “cout”.

Code 1:

#include <iostream>

using namespace std;

int main() {

  cerr<< "An Error occurred here!" << endl;

  return 0;

}

Output:

The message that we type after placing “cerr <<” is now displayed in this outcome which is displayed in the following:

Example 2:

As both the “cin” and “cout” methods as well as “cerr” are declared inside the “iostream” header file, we add the header file here so that we may use them in our code. After that, we have the “std namespace”. Below this, the “main()” is then called. We initialize the “error_str[]” of the “string” data type and assign a message to “error_str[]”. Then, we utilize the “cerr” object where we place the error message and pass this “error_str”. So, when we execute this program, it renders both messages.

Code 2:

#include <iostream>

using namespace std;

int main() {

  char error_str[] = "We can't read the string here!";

  cerr << "Error Occured : " << error_str << endl;

}

Output:

The text that we type after typing “cerr <<” is now visible in the result as well as the message that we added in the “error_str”. The outcome is also shown in the following:

Example 3:

After including the header file and then placing the “std” namespace, we call the “main()” method. After this, the “NumOfLine” integer variable is declared here and initialized with “__LINE__”. This “__LINE__” generates the error messages. Below this, we use the “cerr” object and place the error message which we want to display to the user. We also place the “NumOfLine” variable which shows the line number on which the error occurs in the code.

Code 3:

#include <iostream>

using namespace std;

int main(){

  int NumOfLine = __LINE__;

  cerr << "Error occurred here on the line: " << NumOfLine;

  return 0;

}

Output:

Here, it shows that the error occurs on the “4” line as we added the “__LINE__” on the fourth line of the code. This message is displayed here with the help of the “cerr” object in C++.

Example 4:

We include one more header file, the “fstream”. This “fstream” header file is utilized in C++ to read, write, or create a file as it is the combination of the “ofstream” as well as the “ifstream”. Now, after adding “std namespace” and invoking “main()”, we utilize the “fstream” with the “new_file” variable.

Then, we use the “open()” function here with the “new_file” and pass the name of the file as the parameter. The file name is “myTextFile.txt” which we want to open. Below this, we utilize “if” to pass the “new_file” variable. Now, if the file opens here, the statement after “if” is rendered. Otherwise, the statement after “else” is rendered where we add the “cerr” object to show an error message.

Code 4:

#include <iostream>

#include <fstream>

using namespace std;

int main() {

  fstream new_file;

  new_file.open("myTextFile.txt");

  if(new_file) {

     cout<<"The File is Opened Successfully here!";

  }

  else {

     cerr <<"Error occurred here while opening the file here!";

  }

  return 0;

}

Output:

We can’t open the file that we previously provided. Here, it displays the error message that we inserted after the “cerr” object.

Example 5:

Here, we want to open another file. So, we add both header files and the “std” namespace. Now, we call the “main()”and then utilize the “fstream” with the “t_file” variable. Next, we utilize the “open()” function in this instance with the “new_file” and supply the file name as an argument. The file that we wish to open is called “New.txt”. We use the “if” statement, passing the “t_file” variable. Now, if the file opens, the line that follows “if” is rendered. If not, the statement that follows “else”, where we added the “cerr” object to display an error message, is rendered.

Code 5:

#include <iostream>

#include <fstream>

using namespace std;

int main() {

  fstream t_file;

  t_file.open("New.txt");

  if(t_file) {

    cout<<"The File is Opened here!";

  }

  else {

    cerr <<"Error Occured!";

  }

  return 0;

}

Output:

The file that we provided cannot be opened. So, the error message that we added after the “cerr” object is displayed in the following:

Example 6:

We add an “exception” header file here which is utilized to check for errors that may occur in our code. In the following, we initialize an integer type array named “new_array” of the size “6”. Then, we set the “new_index” of the “int” variable and assign “7” here. Now, we also initialize the “new_size” variable and assign “*(&new_arr + 1) – new_arr” to the “new_size” variable.

After this, we utilize the “try”, “throw”, and “catch” which are used to check the errors and throw the error message. We utilize the “color” object which shows the error message that we added after the “throw” keyword.

Code 6:

#include <iostream>

#include <exception>

using namespace std;

int main() {

 

  int new_arr[6] = {1,9, 4, 3, 8, 7};

  int new_index = 7;

 

  int new_size = *(&new_arr + 1) - new_arr;

  try{

    if(new_index < 0 || new_index >= new_size) throw("Index is not in the Range. It is out of Range here");

 

  else

    cout << new_arr[new_index];

 

  }

  catch(const char* err){

  cerr << err;

  }

  return 0;

}

Output:

Here, it renders an error message which shows that the “Index” is out of range and we get this error by utilizing the “cerr” object.

Example 7:

Here, we check an error that may occur when we divide a number by zero. We create a “d()”function in which we pass two variables of “int” data type “a1” and “a2”. Below this, we add“if” in which we pass the “a2==0” condition. If the value of “a2” is zero, the message that we place after the “throw” is executed which we get by placing the “cerr” object in the code.

After this, we place the “return” which returns the division’s answer if the value of “a2” is not zero. Now, we invoke the “main()” and assign “87” to “x” after initializing it as an “int” variable. After this, we also initialize the “b” and “d_res” variables with “0”. Here, we place the “try” and “catch” which catch the error and the “cerr” throws the error message which we added after the “throw” keyword.

Code 7:

#include <iostream>

using namespace std;

int my_division(int a1, int a2) {

  if( a2 == 0 ) {

    throw "Division by zero is not possible!";

  }

  return (a1/a2);

}

int main () {

  int x = 87;
 
  int y = 0;

  int d_res = 0;

  try {

    d_res = my_division(x, y);

    cout << d_res << endl;

  } catch (const char* msg) {

    cerr << msg << endl;

  }

  return 0;

}

Output:

Here, the error message appears which means that we want to divide the number by “0” which is impossible.

Conclusion

The “cerr” object is studied in detail here. We defined how the “cerr” object aids in displaying the error message in C++ programming. We explored multiple examples where we placed many conditions where the error occurs. We also utilized the “cerr” object after placing the try-catch method and in the file opening code. We showed the code as well as the outcome in which the “cerr” displays an error message.

About the author

Omar Farooq

Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.