close

Exceptions in C++ are implemented using three keywords that work in conjunction with each other: throwtry, and catch.


the first example :

int main()
{
    try
    {
        // Statements that may throw exceptions you want to handle now go here
        throw -1;
    }
    catch (int)
    {
        // Any exceptions of type int thrown within the above try block get sent here
        cerr << "We caught an exception of type int" << endl;
    }
    catch (double)
    {
        // Any exceptions of type double thrown within the above try block get sent here
        cerr << "We caught an exception of type double" << endl;
    }
 
    return 0;
}

the second example :

#include "math.h" // for sqrt() function
using namespace std;
 
int main()
{
    cout << "Enter a number: ";
    double dX;
    cin >> dX;
 
    try // Look for exceptions that occur within try block and route to attached catch block(s)
    {
        // If the user entered a negative number, this is an error condition
        if (dX < 0.0)
            throw "Can not take sqrt of negative number"; // throw exception of type char*
 
        // Otherwise, print the answer
        cout << "The sqrt of " << dX << " is " << sqrt(dX) << endl;
    }
    catch (char* strException) // catch exceptions of type char*
    {
        cerr << "Error: " << strException << endl;
    }
}



ref : http://www.learncpp.com/cpp-tutorial/152-basic-exception-handling/

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 JerryCheng 的頭像
    JerryCheng

    KwCheng's blog

    JerryCheng 發表在 痞客邦 留言(0) 人氣()