C++

C++ 클래스를 이용한 예외 처리

김구티2 2024. 4. 24. 19:40

이번 글에서 우리는 클래스를 이용한 예외 처리를 알아보도록 한다.

 

Problem Statement

① 데이터 멤버 a와 b를 갖는 클래스 Number를 만든다.
② 반복 함수를 작성하여 두 숫자의 GCD(Greatest Common Divisor)를 찾는다.
③ 주어진 수가 소수인지 아닌지 확인하기 위해 반복 함수를 작성한다. 만약 참이라고 판명나면, 클래스 MyPrimeException에 예외를 부여한다.
④ 자신만의 MyPrimeException 클래스를 정의한다.

 

Solution

① 두 개의 데이터 멤버가 있는 Number라는 이름의 클래스를 a와 b로 정의한다.
② 두 개의 멤버 함수를 다음과 같이 정의한다.
   ⑴ int gcd(): 두 숫자의 HCF(Highest Common Factor)를 계산한다.
   ⑵ bool isPrime(): 주어진 숫자가 소수인지 아닌지 확인한다.
③ 데이터 구성원을 초기화하는 데 사용되는 생성자를 사용한다.
④ 예외를 던졌을 때 호출되는 Temporary라는 이름의 다른 클래스를 선택한다.


아래는 클래스를 사용한 예외 처리의 개념을 설명하기 위한 구현이다:

// 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; 

 

출력:

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

728x90