DEV Community

dinhluanbmt
dinhluanbmt

Posted on

C++, try catch , custom exception

Due to performance considerations, I have rarely used try-catch in my works. However, I recently encountered an easy problem on HackerRank about try catch that I couldn't solve.
--> I think we still need some basic about try-cacth^^

//define my own exception class
class mException {
    int val;
public:
    mException(int n = 0) {
        val = n;
    }
    string what() {
        string str = "(mException) error at size = ";
        str.append(to_string(val));
        return str;
    }
};
// just thow some exceptions
bool isValid(string str) {
    size_t size = str.length();
    if (size == 1) throw invalid_argument("invalid argument...length = 1 ");
    if (size < 4) throw mException(size);// thow my custom exception
    if (str[0] == 'A') return true;
    else return false;
}
void test_try_catch(string str) {
    try {
        bool ret = isValid(str);
        if (ret) cout << "Valid..." << endl;
        else cout << "Invalid String" << endl;
    }
    catch (invalid_argument& ex) {
        cout << ex.what() << endl;
    }
    catch (mException& mex) {
        cout << mex.what() << endl;
    }
    catch (...) {
        cout << "other exception..." << endl;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)