Exception Handling using classes in C++ - GeeksforGeeks

07 Apr, 2021
In this article, we will discuss how to handle the exceptions using classes.
Exception Handling:
Exceptions are run-time anomalies or abnormal conditions that a program encounters during its execution.
There are two types of exceptions:Synchronous ExceptionAsynchronous Exception(Ex: which are beyond the program’s control, Disc failure, etc).
Synchronous Exception
Asynchronous Exception(Ex: which are beyond the program’s control, Disc failure, etc).
C++ provides the following specialized keywords for this purpose:try: represents a block of code that can throw an exception.catch: represents a block of code that is executed when a particular exception is thrown.throw: Used to throw an exception. Also used to list the exceptions that a function throws, but doesn’t handle itself.
try: represents a block of code that can throw an exception.
catch: represents a block of code that is executed when a particular exception is thrown.
throw: Used to throw an exception. Also used to list the exceptions that a function throws, but doesn’t handle itself.
Problem Statement:
Create a class Numbers which has two data members a and b.
Write iterative functions to find the GCD of two numbers.
Write an iterative function to check whether any given number is prime or not. If found to be true, then throws an exception to class MyPrimeException.
Define your own MyPrimeException class.
Solution:
Define a class named Number which has two private data members as a and b.
Define two member functions as:int gcd(): to calculate the HCF of the two numbers.bool isPrime(): to check if the given number is prime or not.
int gcd(): to calculate the HCF of the two numbers.
bool isPrime(): to check if the given number is prime or not.
Use constructor which is used to initialize the data members.
Take another class named Temporary which will be called when an exception is thrown.
Below is the implementation to illustrate the concept of Exception Handling using classes:
C++
// C++ program to illustrate the concept// of exception handling using class  #include <bits/stdc++.h>using namespace std;  // Class declarationclass Number {private:    int a, b;  public:    // Constructors    Number(int x, int y)    {        a = x;        b = y;    }      // Function that find the GCD    // of two numbers a and b    int gcd()    {        // While a is not equal to b        while (a != b) {              // Update a to a - b            if (a > b)                a = a - b;              // Otherwise, update b            else                b = b - a;        }          // Return the resultant GCD        return a;    }      // Function to check if the    // given number is prime    bool isPrime(int n)    {        // Base Case        if (n <= 1)            return false;          // Iterate over the range [2, N]        for (int i = 2; i < n; i++) {              // If n has more than 2            // factors, then return            // false            if (n % i == 0)                return false;        }          // Return true        return true;    }};  // Empty classclass MyPrimeException {};  // Driver Codeint main(){    int x = 13, y = 56;      Number num1(x, y);      // Print the GCD of X and Y    cout << "GCD is = "         << num1.gcd() << endl;      // If X is prime    if (num1.isPrime(x))        cout << x             << " is a prime number"             << endl;      // If Y is prime    if (num1.isPrime(y))        cout << y             << " is a prime number"             << endl;      // Exception Handling    if ((num1.isPrime(x))        || (num1.isPrime(y))) {          // Try Block        try {            throw MyPrimeException();        }          // Catch Block        catch (MyPrimeException t) {              cout << "Caught exception "                 << "of MyPrimeException "                 << "class." << endl;        }    }      return 0;}
GCD is = 1
13 is a prime number
Caught exception of MyPrimeException class.

C++-Exception Handling
CPP-Basics
cpp-exception
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Sorting a vector in C++
Friend class and function in C++
std::string class in C++
Header files in C/C++ and its uses
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
C++ Program for QuickSort
Sorting a Map by value in C++ STL