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: henrytien@hotmail.com
 *
 * \brief 
 *
 * TODO: long description
 *
 * \note
*/
#include <iostream>
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;
}
输出效果
2017-02-21_205451.png
2017-02-21_205511.png
/*!
 * \file cinexep.cpp
 * \date 2017/02/21 21:08
 *
 * \author henry
 * Contact: henrytien@hotmail.com
 *
 * \brief 
 *
 * TODO: long description
 *
 * \note
*/
#include <iostream>
#include <exception>
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;
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容