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

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

Sentry image

See why 4M developers consider Sentry, β€œnot bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

πŸ‘‹ Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay