Exception Handling using classes in C++
Last Updated :
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 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:
- Define a class named Number which has two private data members as a and b.
- Define two member functions as:
- 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++
#include <bits/stdc++.h>
using namespace std;
class Number {
private :
int a, b;
public :
Number( int x, int y)
{
a = x;
b = y;
}
int gcd()
{
while (a != b) {
if (a > b)
a = a - b;
else
b = b - a;
}
return a;
}
bool isPrime( int n)
{
if (n <= 1)
return false ;
for ( int i = 2; i < n; i++) {
if (n % i == 0)
return false ;
}
return true ;
}
};
class MyPrimeException {
};
int main()
{
int x = 13, y = 56;
Number num1(x, y);
cout << "GCD is = "
<< num1.gcd() << endl;
if (num1.isPrime(x))
cout << x
<< " is a prime number"
<< endl;
if (num1.isPrime(y))
cout << y
<< " is a prime number"
<< endl;
if ((num1.isPrime(x))
|| (num1.isPrime(y))) {
try {
throw MyPrimeException();
}
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.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...