当前位置: 移动技术网 > IT编程>开发语言>C/C++ > c++ try_throw_catch异常处理

c++ try_throw_catch异常处理

2019年05月28日  | 移动技术网IT编程  | 我要评论

网址大全吧,赵秉哲,云裳小丫鬟

参考https://www.cnblogs.com/xiaojianliu/articles/8900795.html

在程序设计时,针对不同的异常情况,预先设定异常信息,在程序运行时,根据异常提示信息可以有效的定位异常,找出异常原因。

try_throw_catch异常处理处理伪代码:

try { //尝试捕获异常 
    if (满足异常) throw 异常标志符;  //抛出异常
}
catch (异常类型) {  //异常处理
    cerr << "异常描述信息";
}

举例:输入参数异常处理

#include<iostream>
#include <string>
using namespace std;

//int main(int argc, char** argv)
int main()
{
    int argc = 1;
    try {    //尝试捕获异常
        if (argc == 1) throw std::string("invalid command line parameter.");    //假如输入参数个数只有1个,抛出异常
    }
    catch (std::string& s) {    //异常处理
        std::cerr << s << std::endl;    //s为抛出的异常标志
        std::cerr << "正确用法: "<< "project.exe"<<" "
            << "inputdir"<<" "
            << "outputdir\n"
            << std::endl;

        system("pause");
        return exit_failure;
    }

    system("pause");
    return 0;
}

输出结果:

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网