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

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more