The Wayback Machine - https://web.archive.org/web/20240711032836/https://www.geeksforgeeks.org/exception-handling-using-classes-in-cpp/
Open In App

Exception Handling using classes in C++

Last Updated : 07 Apr, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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

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:

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 declaration
class 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 class
class MyPrimeException {
};
  
// Driver Code
int 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;
}


Output:

GCD is = 1
13 is a prime number
Caught exception of MyPrimeException class.


Previous Article
Next Article

Similar Reads

Comparison of Exception Handling in C++ and Java
Both languages use to try, catch and throw keywords for exception handling, and their meaning is also the same in both languages. Following are the differences between Java and C++ exception handling: Java C++ Only throwable objects can be thrown as exceptions.All types can be thrown as exceptions.We can catch Exception objects to catch all kinds o
4 min read
Exception Handling and Object Destruction in C++
An exception is termed as an unwanted error that arises during the runtime of the program. The practice of separating the anomaly-causing program/code from the rest of the program/code is known as Exception Handling. An object is termed as an instance of the class which has the same name as that of the class. A destructor is a member function of a
4 min read
C++ | Exception Handling | Question 1
#include &lt;iostream&gt; using namespace std; int main() { int x = -1; try { cout &lt;&lt; &quot;Inside try \n&quot;; if (x &lt; 0) { throw x; cout &lt;&lt; &quot;After throw \n&quot;; } } catch (int x ) { cout &lt;&lt; &quot;Exception Caught \n&quot;; } cout &lt;&lt; &quot;After catch \n&quot;; return 0; } (A) Inside try Exception Caught After th
1 min read
C++ | Exception Handling | Question 2
What is the advantage of exception handling ? Remove error-handling code from the software's main line of code. A method writer can choose to handle certain exceptions and delegate others to the caller. An exception that occurs in a function can be handled anywhere in the function call stack. (A) Only 1 (B) 1, 2 and 3 (C) 1 and 3 (D) 1 and 2 Answer
1 min read
C++ | Exception Handling | Question 3
What should be put in a try block? 1. Statements that might cause exceptions 2. Statements that should be skipped in case of an exception (A) Only 1 (B) Only 2 (C) Both 1 and 2 Answer: (C)Explanation: The statements which may cause problems are put in try block. Also, the statements which should not be executed after a problem occurred, are put in
1 min read
C++ | Exception Handling | Question 4
Output of following program #include&lt;iostream&gt; using namespace std; class Base {}; class Derived: public Base {}; int main() { Derived d; try { throw d; } catch(Base b) { cout&lt;&lt;&quot;Caught Base Exception&quot;; } catch(Derived d) { cout&lt;&lt;&quot;Caught Derived Exception&quot;; } return 0; } (A) Caught Derived Exception (B) Caught B
1 min read
C++ | Exception Handling | Question 5
#include &lt;iostream&gt; using namespace std; int main() { try { throw 'a'; } catch (int param) { cout &lt;&lt; &quot;int exception\n&quot;; } catch (...) { cout &lt;&lt; &quot;default exception\n&quot;; } cout &lt;&lt; &quot;After Exception&quot;; return 0; } (A) default exception After Exception (B) int exception After Exception (C) int exceptio
1 min read
C++ | Exception Handling | Question 6
#include &lt;iostream&gt; using namespace std; int main() { try { throw 10; } catch (...) { cout &lt;&lt; &quot;default exception\n&quot;; } catch (int param) { cout &lt;&lt; &quot;int exception\n&quot;; } return 0; } (A) default exception (B) int exception (C) Compiler Error Answer: (C) Explanation: It is compiler error to put catch all block befo
1 min read
C++ | Exception Handling | Question 7
#include &lt;iostream&gt; using namespace std; int main() { try { try { throw 20; } catch (int n) { cout &lt;&lt; &quot;Inner Catch\n&quot;; throw; } } catch (int x) { cout &lt;&lt; &quot;Outer Catch\n&quot;; } return 0; } (A) Outer Catch (B) Inner Catch (C) Inner Catch Outer Catch (D) Compiler Error Answer: (C) Explanation: The statement 'throw;'
1 min read
C++ | Exception Handling | Question 8
#include &lt;iostream&gt; using namespace std; class Test { public: Test() { cout &lt;&lt; &quot;Constructing an object of Test &quot; &lt;&lt; endl; } ~Test() { cout &lt;&lt; &quot;Destructing an object of Test &quot; &lt;&lt; endl; } }; int main() { try { Test t1; throw 10; } catch(int i) { cout &lt;&lt; &quot;Caught &quot; &lt;&lt; i &lt;&lt; en
1 min read
three90RightbarBannerImg