Open In App

C++ Program to Handle the Exception Methods

Last Updated : 30 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Exception handling is a manner to handle the runtime error, we carry out exception handling, so, the normal flow of the program may be maintained even after runtime errors. Exceptions are runtime anomalies or abnormal conditions that a program encounters during its execution. 

The Exception Handling mechanism offers a way to transfer control from one part of a program to another, This makes it clean to separate the mistake handling code from the code written to address the real functionality of the program.

C++ provides the following specialized keywords for exception handling:

  1. try: A block of code that may throw an exception is typically placed inside the try block, It’s followed by one or extra seize blocks. If an exception happens, it is thrown from the try block.
  2. catch: This block catches the exception thrown from the try block, code to address the exception is written inside this catch block.
  3. throw: throw keyword is used to throw an exception. Also used to list the exceptions that a function throws but doesn’t handle itself.

Syntax:

try 
{
    // Block of code to try
  
    // Throw an exception when a problem arise
   throw exception;
}
catch () 
{
    // Block of code to handle errors
}

Below are the C++ programs to show how exceptions are handled in C++:

Example 1: Below is the C++ program to show what happens when division by zero is done and exceptions are not handled.

C++




// C++ program to show what happens 
// when division by zero is done 
// and exceptions are not handled
#include <iostream>
using namespace std;
  
// Driver code
int main() 
{
  int numerator = 5;
  int denominator = 0;
    
  int ans = numerator/denominator;
    
  // The result will not be displayed 
  cout << ans << endl;
    
  return 0;
    
}


Output:

Floating-point exception (SIGFPE)

The above program will show an abnormal behavior and the output will not be displayed. An exception is being thrown in the code but it is not being caught so either it will show a floating-point exception or not display any output.

Below is the C++ program to handle divide by zero exception:

C++




// C++ program to handle 
// divide by zero exception
#include <iostream>
using namespace std;
  
// Driver code
int main() 
{
  int numerator = 5;
  int denominator = 0;
  int result;
    
  try
  {
    if(denominator == 0)
    {
      throw denominator;
    }
    result = numerator / denominator;
  }
  catch(int ex)
  {
    cout << "Exception: Divide by zero not allowed :" << 
             ex << endl;
  }
  cout << "Division Result is: " << result;
    
  return 0;
}


Output

Exception: Divide by zero not allowed :0
Division Result is: 4197440

Example 2: Below is the C++ program to input an age integer if the age is less than 18 then return NO, but if the age is greater than or equal to 18 then return Yes:

C++




// C++ program to input an age integer 
// if the age is less than 18 then 
// return NO, but if the age is greater
// than or equal to 18 then return Yes
#include <iostream>
using namespace std;
  
// Driver code
int main() 
{
  try 
  {
    int age = 10;
    if (age >= 18) 
    {
      cout << "YES, you are old enough.";
    
    else 
    {
      throw (age);
    }
  }
  catch (int num) 
  {
    cout << "No, You must be at least 18 years old" <<
             endl;
    cout << "Age is: " << num;  
  }
  return 0;
}


Output

No, You must be at least 18 years old
Age is: 10

C++ Standard Exceptions

C++ defines a set of standard exceptions defined in <exception> which can be used in the programs. These exceptions are arranged in the parent-child class hierarchy. Below is the table listing the standard exceptions with description:

S.No. Exception Description
1. std::exception An exception and parent class of all the standard C++ exceptions.
2. std::bad_alloc This exception can be thrown by new.
3. std::bad_cast This exception can be thrown by dynamic_cast.
4. std::bad_exception  This exception is a useful device to handle unexpected exceptions in a C++ program.
5. std::bad_typeid This can be thrown by type id.
6. std::logic_error An exception that can be detected by reading the code.
7. std::domain_error This is an exception thrown when a mathematically invalid domain is used.
8. std::invalid_argument This exception is thrown due to invalid arguments.
9. std::length_error This exception is thrown when a too big std::string is created.
10. std::out_of_range This can be thrown by the ‘at’ method, for example a std::vector and std::bitset<>::operator[]().
11. std::runtime_error An exception that theoretically cannot be detected by reading the code
12. std::overflow_error This is thrown if a mathematical overflow occurs.
13. std::range_error This occurs when you try to store a value that is out of range.
14. std::underflow_error This is thrown if a mathematical underflow occurs.

New Exception in C++

The customized exceptions can be defined by inheriting and overriding exception class functionality.

Syntax:

 use std::exception

Below is the C++ program to define a new exception:

C++




// C++ program to define a 
// new exception
#include <iostream>
#include <exception>
using namespace std;
  
struct Exceptions : public exception 
{
   const char* Except() const throw () 
   {
      return "GeeksforGeeks";
   }
};
   
// Driver code
int main() 
{
  try 
  {
    throw Exceptions();
  
  catch(Exceptions& it) 
  {
    cout << "Customised Exception caught" << 
             endl;
    cout << it.Except() <<endl;
  
  catch(std::exception& it) 
  {}
}


Output

Customised Exception caught
GeeksforGeeks


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads