[C++/Classes] Exceptional Server

kkanyo·2022년 1월 15일

문제


Link: Exeptional Server | HackerRank

주어진 Server 클래스의 멤버 함수인 compute 의 동작에서 발생하는 예외를 처리하는 문제입니다.


풀이


        ...
        
        // When you use multiple catch blocks, have to consider order.
        // In this problem, 'exception' is parent exception object of 'bad_alloc'.
        // If exception be first, catch block for bac_alloc do not run.
        try { 
            cout << Server::compute(A, B) << endl;
        }
	catch (const exception& e) {		// standard c++ exception
            cout << "Exception: " << e.what() << endl;    
        }
        catch (const bad_alloc& e) {		// DO NOT RUN!!
            cout << "Not enough memory\n";
        }
        catch (int i) {				// throw integer
            cout << "Other Exception\n";
        }
        
       	...

catch문이 반복적으로 사용될 때 순서를 고려해야 합니다.

exception 클래스의 파생 클래스 중 하나인 bad_alloc 은 저장공간 할당에 실패했을 경우 예외를 발생시킵니다.

위 코드의 경우 기본 클래스인 exception 에 대한 catch 문이 먼저 올 경우, bad_alloc 에 관한 예외가 발생하더라도 첫번째 catch 문에 기본 클래스의 참조로 전달되며 두번째 catch 문은 실행되지 않습니다.

        try { 
            cout << Server::compute(A, B) << endl;
        }
        catch (const bad_alloc& e) {		// fail to allocate the memory
            cout << "Not enough memory\n";
        }
        catch (const exception& e) {		// standard c++ exception
            cout << "Exception: " << e.what() << endl;    
        }
        catch (int i) {				// throw integer
            cout << "Other Exception\n";
        }
        //--------------

따라서, 위와 같이 bac_alloc 예외에 대한 catch 문을 먼저 처리할 수 있도록 순서를 고려해야합니다.


전체 코드


#include <iostream>
#include <exception>
#include <string>
#include <stdexcept>
#include <vector>
#include <cmath>
using namespace std;

class Server {
private:
	static int load;
public:
	static int compute(long long A, long long B) {
		load += 1;
		if(A < 0) {
			throw std::invalid_argument("A is negative");
		}
		vector<int> v(A, 0);
		int real = -1, cmplx = sqrt(-1);
		if(B == 0) throw 0;
		real = (A/B)*real;
		int ans = v.at(B);
		return real + A - B*ans;
	}
	static int getLoad() {
		return load;
	}
};
int Server::load = 0;

int main() {
	int T; cin >> T;
	while(T--) {
		long long A, B;
		cin >> A >> B;
        
	/* Enter your code here. */
        try { 
            cout << Server::compute(A, B) << endl;
        }
        catch (const bad_alloc& e) {		//fail to allocate the memory
            cout << "Not enough memory\n";
        }
        catch (const exception& e) {		//standard c++ exception
            cout << "Exception: " << e.what() << endl;    
        }
        catch (int i) {     			//throw integer
            cout << "Other Exception\n";
        }
        //--------------
        
	}
	cout << Server::getLoad() << endl;
	return 0;
}

참고


std::bad_alloc | cppreference.com

profile
"Engineering is the closest thing to magic that exists in the world." - Elon Musk

0개의 댓글