C++ 异常操作

key word

  • throw
  • catch
  • try

语法:

try
{
    // protected code
}
catch (CMemoryException* e)
{
    
}
catch (CFileException* e)
{
}
catch (CException* e)
{

}

Catching Exceptions

try {
    // protected code
}
catch (Exception e) {
    // code to handle exceptionName exception
}

Demo


/*!
 * \file hand_exception.cpp
 * \date 2017/02/21 21:04
 *
 * \author henry
 * Contact: [email protected]
 *
 * \brief 
 *
 * TODO: long description
 *
 * \note
*/
#include 
using namespace std;

double division(int a, int b) {
    if (b == 0) {
        throw "Division is zero";
    }
    return a / b;

}

int main() {

    int a = 12;
    int b = 0;
    double z = 0;
    try {
        z = division(a, b);
        cout << z << endl;
    }
    catch (const char *msg) {
        cerr << msg << endl;
    }
    system("pause");
    return 0;
}
输出效果
C++ 异常操作_第1张图片
2017-02-21_205451.png
C++ 异常操作_第2张图片
2017-02-21_205511.png
/*!
 * \file cinexep.cpp
 * \date 2017/02/21 21:08
 *
 * \author henry
 * Contact: [email protected]
 *
 * \brief 
 *
 * TODO: long description
 *
 * \note
*/
#include 
#include 
using std::cout;
using std::cin;
using std::endl;
using namespace std;
int main() {

    //have failbit cause an exception to be thrown
    cin.exceptions(ios_base::failbit);
    int sum = 0;
    int input = 0;
    cout << "Enter a number:";
    try{
        while (cin >> input) {
            sum += input;
        }
    }catch (ios_base::failure &bf) {
        cout << bf.what() << endl;
        cout << "*_* " << endl;
    }
    
    cout << "last input entered=" << input << endl;
    cout << "sum = " << sum << endl;
    system("pause");
    return 0;
}

你可能感兴趣的:(C++ 异常操作)