Coding Test/HackerRank

[C++/Classes] Exceptional Server

깐요 2022. 1. 15. 15:20

문제


Link: Exeptional Server | HackerRank

 

Exceptional Server | HackerRank

Handle server errors.

www.hackerrank.com

주어진 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 문에 exception 객체의 인수로 전달되어 두번째 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

std::bad_alloc is the type of the object thrown as exceptions by the allocation functions to report failure to allocate storage. [edit] Member functions constructs a new bad_alloc object (public member function) replaces the bad_alloc object (public member

en.cppreference.com

320x100

'Coding Test > HackerRank' 카테고리의 다른 글

[C++/STL] Deque-STL  (0) 2022.01.16
[C++/Class] Abstract Classes - Polymorphism  (0) 2022.01.15
[C++/Classes] Virtual Functions  (0) 2022.01.15
[C++/Classes] Inherited Code  (0) 2022.01.09
[C++/Classes] Box it!  (0) 2022.01.09