Min menu

Pages

VB

Exceptions in C++ | C Plus Plus

The concept of error handling inC++

Error handling(Exceptions Handling)It is intended to write code that may cause any problem in the program in a way that ensures that if the expected error or any other error occurs, the program will not hang or close suddenly.

The sudden appearance of an error in the program is very bad because it alienates a large number of users and their unwillingness to return to using this program again.


Types of errors in C++

  • grammatical errors(Syntax Errors)It is intended to violate the principles of language, such as defining something incorrectly or forgetting to put a semicolon.

  • Errors that occur while running the program are called exceptions(Exceptions)Which causes it to hang and stop abnormally.

  • logical errors(Logical Errors)It means that the code works without any problems, but the result of running this code is incorrect.

So, any software error that occurs with you while running the program is called an exception(Exception)Even if the error name contains the wordError.
In other words, anyErrorIt appears to you while the program is runningException.

In this lesson, you will learn how to avoid errors in the programs you write, and actually you will learn how to prepare the program to deal with errors that may occur during its operation so that the program is always running in the eyes of the user and does not show him any errors.



Some of the reasons that cause an exception in C++

  • In the event that the program connects to the network and suddenly the connection is cut off.

  • If the program is trying to read information from a text file, and this file does not exist.

  • In the event that the program is trying to create or delete a file, but it does not have the authority to do so.



Technical information 

In case the code you wrote contains grammatical errors(Syntax Errors)You must fix them all so that the compiler can convert the code you wrote into code that the computer understands and then executes for you. That is, you cannot protect the program from those present in the code itself, but you can protect it from problems that may occur at the time of the operation of this code.


In this lesson, you will learn how ready-made libraries that you may use in the future in your projects are made to show errors if you do not use them properly.
Knowing this is also very important to you, because you will be able to share the code that you are preparing with other programmers and show errors in it if they do not use it correctly.

Examples of types of errors inC++

In the following example, we did not put a semicolon at the end of the command cout, which will cause a problem when the compiler tries to run the program.
So the following code contains a syntax error(Syntax Error).

first example

main.cpp
#include <iostream>
	  
		  using namespace std;
	  
		  int main()
		  {
		  int x = 10;
	  
		  cout << x
	  
		  return 0;
		  }
	

The following error will appear when running, which means that the compiler expects you to put a semicolon at the end of the ninth line.

main.cpp|9|error: expected ';' before 'return'|


In the following example, we created a program that prints for the student whether he passed or failed based on his final grade.
It is assumed that a student will be considered failing if his GPA is between 0 and .9.9 ,And it is considered successful if its average is 10 and20 .
Here we deliberately put a logical error(Logical Error)Whereas, when printing the student's result, we were not sure whether the rate was between 0 as a minimum and 20 as a maximum.

second example

main.cpp
#include <iostream>
	  
		  using namespace std;
	  
		  int main()
		  {
		  float average = 25;
	  
		  if (average < 10)
		  {
		  cout << "The student failed the exam";
		  }
		  else if (average >= 10)
		  {
		  cout << "The student passed the exam";
		  }
	  
		  return 0;
		  }
	  
	

We will get the following result when running and we note that there is no software problem that caused the code to stop, but we know that there is a logical problem in the code because the rate on which the success sentence was printed is an impossible rate to be real.

The student passed the exam

word throwinC++

This word is used to throw an exception, ie to show that there is a problem with the program.


In the following example, we created a function whose name divide()when called, we pass two numbers to it, and it returns the result of dividing the first number by the second number.
Here if the second number passed to the function (the divisor) is zero, an exception will be thrown which is a plain text that in mathematics is not divisible by zero.

Example

main.cpp
#include <iostream>
	  
		  using namespace std;
	  
		  // When called, we pass it two numbers and it returns the result of dividing the first number by the second number divide() Here we have defined a function named
		  double divide(double a, double b)
		  {
		  // is 0, an exception b will be thrown if the second number to be passed to the parameter is
		  if (b == 0)
		  {
		  throw "Math Error, you can't divide by 0";
		  }
	  
		  // If no exception is thrown, the quotient will be returned
		  return a / b;
		  }
	  
		  // main() Here we have defined the function
		  int main()
		  {
		  // and pass two numbers to it and then print the quotient that divide() will return here we called the function
		  cout << divide(5, 2) << endl;
	  
		  // and passing 0 in place of the second parameter, which will throw an exception and stop the program completely divide() Here we called the function
		  cout << divide(5, 0) << endl;
	  
		  return 0;
		  }
	

We will get the following result when running.

Notice that it shows you the result of dividing the first two numbers, which is 2.5successful.

And when it tries to display the result of the second two numbers, it tells you that the program has stopped working because an exception was thrown.

2.5
		  terminate called after throwing an instance of 'char const*'
	

In addition, a pop-up window appears informing you that the program has stopped suddenly due to a problem with it.


The reason the program stops when the function throws an exception is that we did not call the function devide()securely even though we know that it may cause the program to hang, and by that we mean that we did not use the two statements tryas catchwe are supposed to do.

If you're wondering why the statement didn't appear "Math Error, you can't divide by 0"when the function threw the exception, it's because we didn't handle the thrown exception like it was supposed to and of course you'll learn how to do that soon.

The two sentences tryand catchinC++

Exception catch(Exception Catching)It is a method that allows you to protect the program from any code that you suspect may cause any error, and to achieve this we use the two sentences tryandcatch.

In general, any questionable code should be placed within the bounds of the sentencetry.
Any problem that occurs in the sentence catchis dealt with within its sentence limits tryas follows.

try
		{
		// Protected Code
		// Here we write commands that may cause an exception
		}
		catch(ExceptionType e)
		{
		// Error Handling Code
		// Throw a try exception here. We write commands that tell the program what to do if the
		}
  

The code we put inside the sentence tryis calledProtected CodeThis means that the program is protected from any error that may occur due to this code.
The code we put inside the sentence catchis calledError Handling CodeIt is the code that will handle the exception that may be caught.


Important note

When you use the sentence tryeven if you don't put any code inside it, you are forced to put the sentence catchafter it.
You can also put more than one sentence catchin case the code may cause more than one error.


In the following example, we created a function whose name devide()when called, we pass two numbers to it, and it returns the result of dividing the first number by the second number.
Here if the second number passed to the function (the divisor) is zero, an exception will be thrown which is a plain text that in mathematics is not divisible by zero.

Since the function devide()can cause an error when it is called we put it insidetry/catch

first example

main.cpp
#include <iostream>
	  
		  using namespace std;
	  
		  // When called, we pass it two numbers and it returns the result of dividing the first number by the second number divide() Here we have defined a function named
		  double divide(double a, double b)
		  {
		  // is 0, an exception b will be thrown if the second number to be passed to the parameter is
		  if (b == 0)
		  {
		  throw "Math Error, you can't divide by 0";
		  }
	  
		  // If no exception is thrown, the quotient will be returned
		  return a / b;
		  }
	  
		  // main() Here we have defined the function
		  int main()
		  {
		  // and passing 0 in place of the second parameter, which will throw a divide() exception here we called the function
		  try
		  {
		  cout << divide(5, 0) << endl;
		  }
		  // e The exception to be thrown will be a string (a string of characters) and these characters will be passed as a value to the variable
		  catch (char const* e)
		  {
		  // e Here we print the text of the thrown exception and store it in the variable
		  cout << e << endl;
		  }
	  
		  // Here the following command will be executed very normally because the exception that occurred before has been handled
		  cout << "The program is still working properly :)";
	  
		  return 0;
		  }
	

We will get the following result when running.

Math Error, you can't divide by 0
		  The program is still working properly :)
	

very important information

The reason for making the parameter type eis char const*that we noticed in the previous example that the text that is thrown as an exception has its type as well.

Important concepts about error handling inC++


  How to define a function that does  throw more than one number of their type  int and how to call it.


Here we have given an example of how to define a function that does throwmore than one number of their type intas well as how to call it.

In the following example, we have defined a function whose name compareAges()when called, we pass two numbers to it, the first number being the age of the son and the second being the age of his mother.
The function will compare the age of the son with the age of his mother and return the difference between them provided that the numbers we pass to them are considered logically acceptable numbers, otherwise it will throw an exception.

Example

main.cpp
      #include <iostream>
	  
		  using namespace std;
	  
		  // when called we pass it two numbers and it returns a number representing the difference between them compareAges() Here we have defined a function named
		  int compareAges(int sonAge, int momAge)
		  {
		  // If the son's age is greater than or equal to the mother's age, an exception numbered 1 will be thrown
		  if (sonAge >= momAge)
		  throw 1;
	  
		  // If the child's age is less than or equal to zero, an exception number 2 will be thrown
		  else if (sonAge <= 0)
		  throw 2;
	  
		  // If the age of the mother is less than or equal to zero, an exception number 3 will be thrown
		  else if (momAge <= 0)
		  throw 3;
	  
		  // If the difference between the age of the mother and the son is not at least 12 years, an exception number 4 will be thrown
		  else if (momAge - sonAge < 12)
		  throw 4;
	  
		  // If no exception is thrown, the age difference will be returned
		  return momAge - sonAge;
		  }
	  
		  // main() Here we have defined the function
		  int main()
		  {
		  // and pass two integers to it that represent the age of a command and the age of its son to see if the entered ages are considered acceptable or not compareAges() here we called the function
		  try
		  {
		  compareAges(26, 24);
		  }
		  // e The exception to be thrown will be a string (a string of characters) and these characters will be passed as a value to the variable
		  catch (int e)
		  {
		  switch(e)
		  {
		  case 1:
		  cout << "Error: Son's age can't be less than his mom! \n";
		  break;
		  case 2:
		  cout << "Error: Son's age can't be less than or equal zero \n";
		  break;
		  case 3:
		  cout << "Error: Mom's age can't be less than or equal zero \n";
		  break;
		  case 4:
		  cout << "Error: Mom's age should be 12 years bigger than son age \n";
		  break;
		  }
		  }
	  
		  // Here the following command will be executed very normally because the exception that occurred before has been handled
		  cout << "The program is still working properly :)";
	  
		  return 0;
		  }
    

We will get the following result when running.

      Error: Son's age can't be less than his mom!
		  The program is still working properly :)
    


  How to use the code  ... to protect the code from any exception

Here we have put an example on how to use the code ...to protect the code from any exception that might happen even if we don't know what kind of exception might be thrown.

If you do not know the type of exception that the code may cause, or you only know some types of exceptions that may occur and you want to protect the code from all the exceptions that may occur, you can put the code ...only in the function catch()as follows.

    try
		{
		// Here we write commands that may cause an exception
		}
		catch(...)
		{
		// The compiler will jump here to try any exception that occurs in the statement
		}
  


In the following example, we have defined a function whose name checkAge()when called, we pass to it a number representing the age, so it checks on it and shows errors if the age is less than or equal to 0or greater than 130or less than18.

Example

main.cpp
      #include <iostream>
	  
		  using namespace std;
	  
		  // When called, we pass an age number to it. checkAge() Here we have defined a function called
		  void checkAge(int age)
		  {
		  // If the age passed to it is less than or equal to 0 it will throw an exception
		  if (age <= 0)
		  throw "Error: Entered age can't be less or equal zero!";
	  
		  // If the age passed to it is greater than 130, an exception will be thrown
		  if (age > 130)
		  throw "Error: Entered age is impossible!";
	  
		  // If the age passed to her is younger than 18 she will throw an exception
		  if (age < 18)
		  throw "Error: You are not allowed!";
	  
		  // If no exception is thrown, the next print command will be executed, which means the age is acceptable
		  cout << "Age confirmed!";
		  }
	  
	  
		  // main() Here we have defined the function
		  int main()
		  {
		  // and passing the value 15 its checkAge() here we called the function
		  try
		  {
		  checkAge(15);
		  }
		  // catch it and print the catch() clause in it. The try function will return any exception thrown in the clause
		  catch (...)
		  {
		  cout << "Oops.. Something is not right!";
		  }
	  
		  return 0;
		  }
    

We will get the following result when running.

      Oops.. Something is not right!
		


 How to put more than one  catch in case the code may cause exceptions of more than one type.

Here we have an example of how to put more than one catchin case the code may cause exceptions of more than one type.

In the following example, we have defined a function whose name checkWord()when called, we pass a text to it to check and check whether it contains one word or not.
The function will throw a count-valued exception 0if an empty string is passed to it, and a word-valued exception 'Space'if more than one word is passed to it.

Example

main.cpp
      #include <iostream>
	  
		  using namespace std;
	  
		  // When called, we pass the checkWord() script to it. Here we have defined a function called
		  checkWord(string s)
		  {
		  // If the text being passed does not contain any characters, an exception will be thrown, which is an integer with a value of 0
		  if (s.empty())
		  throw 0;
	  
		  // "Space" If the passed text contains an empty space an exception will be thrown with a value of
		  if (s.find(" ") != string::npos)
		  throw "Space";
		  }
	  
		  // main() Here we have defined the function
		  int main()
		  {
		  // Here we have defined the text that we will check for
		  string s = "Hello Word!";
	  
		  // s to check the value of the checkWord() variable here we called the function
		  try
		  {
		  checkWord(s);
		  }
		  // If an exception valued at 0 is thrown, it will be handled here
		  catch(int e)
		  {
		  cout << "Error: string length is empty! \n";
		  }
		  // It will be handled here, if a keyword exception is thrown
		  catch(char const* e)
		  {
		  cout << "Error: string contain a whitespace!\n";
		  }
		  // If an exception of any other type is thrown, it will be handled here
		  catch(...)
		  {
		  cout << "Error: something is not right! \n";
		  }
	  
		  cout << "The program is still working properly :)";
	  
		  return 0;
		  }
    

We will get the following result when running.

      Error: string containing a whitespace!
		  The program is still working properly :)
    


 How to define and use a new exception type.

Here we have an example of how to define and use a new exception type.

Default exceptions inC++

Before explaining how to define a new exception, you should know how ready-made exceptions are built into the language.
In general std::exceptionit is the base class for any exception that is defined so any class that is an exception must inherit from it.
After he inherits from him, he must doOverrideThe function has its name what()to specify the value of the exception to be thrown.

The following image shows you the ready-made exceptions inC++And how does she inherit from the class?std::exception.


Example of how to define a new exception inC++

In the following example, we have defined a class with its name MyExceptionand made it inherit from the class exceptionto represent an exception.
In this class we have redefined the function what()to make it throw a string exception when it is called.

Example

main.cpp
      #include <iostream>
		  #include <exception>
	  
		  using namespace std;
	  
		  // Because we want it to be an exception that inherits from the MyException class, here we have defined a class named
		  class MyException : public exception
		  {
		  public:
		  // To make it throw the exception we want when we call it what() here we have defined the function
		  const char* what() const throw ()
		  {
		  return "My Exception is thrown! \n";
		  }
		  };
	  
		  // main() Here we have defined the function
		  int main()
		  {
		  // in it what() so we can call the myExcep function called MyException Here we created an object from the class
		  MyException myExcep;
	  
		  // in it automatically what() which in turn will call the myExcep function here we threw an exception of its type
		  try
		  {
		  throw myExcep;
		  }
		  // in it what() will call the MyException function here we said that if the thrown exception is of its type
		  catch(MyException& e)
		  {
		  cout << e.what();
		  }
		  // and here we mean what kind was an exception here we said that if the thrown exception was of its type
		  catch(exception& e)
		  {
		  // Here you can write what we want to do in case of any other exception
		  }
	  
		  cout << "The program is still working properly :)";
		  }
    

We will get the following result when running.

      My Exception is thrown!
		  The program is still working properly :)