c++ try catch throw 简单用法
来源:互联网 发布:金山软件king计划 编辑:程序博客网 时间:2024/05/21 14:05
tyr catch throw 是c++的异常处理机制,当程序遇到一些意外的错误,(比如除数为0) 这是程序员可以使用一些基本的方法来处理这些异常
首先看一个处理除数遇到0的例子
#include <iostream>using std::cout;using std::cin;using std::cerr;int fun(int & a, int & b){if(b == 0){throw "hello there have zero sorry\n"; //引发异常}return a / b;}int main(){int a;int b;while(true){cin >> a;cin >> b;try //try里面是可能引发异常代码块{cout << " a / b = "<< fun(a,b) << "\n";}catch(const char *str) 接收异常,处理异常{cout << str;cerr <<"除数为0\n"; //cerr不会到输出缓冲中 这样在紧急情况下也可以使用}}system("pause");return 1;}try:try块标识符其中特定的异常可能被激活的代码块,他后面跟一个或者多个catch块.
catch:类似于函数定义,但并不是函数定义,关键字catch表明这是给一个处理程序, 里面的const cahr *str 会接受throw传过来错误信息.
throw:抛出异常信息,类似于执行返回语句,因为它将终止函数的执行,但是它不是将控制权交给调用程序,而是导致程序沿着函数调用序列后退,知道找到包含try块的函数.
---[部分来自c++ primer plus]
0 0
- c++ try catch throw 简单用法
- c++ try catch throw 简单用法
- try catch throw用法
- try catch throw用法
- try catch throw用法
- try catch throw用法
- try catch throw用法
- try catch throw用法
- try catch throw用法
- try catch throw用法
- try catch throw用法
- c++ try catch throw 用法
- js中try/catch/throw的用法
- 异常控制try-throw-catch用法小结
- try catch 以及 throw 的用法
- 【c#】异常处理:try catch throw
- C/C++编程异常处理中try和throw以及catch语句的用法
- try...catch...throw
- hdu 2222(AC自动机 裸题)
- Mac下配置 Android ndk 开发环境
- 多线程学习总结
- Maven下载,配置,创建项目
- 使用StarUML创建类图
- c++ try catch throw 简单用法
- Android Studio之gradle的配置与介绍
- 【renice】调整进程的nice值,即调整进程的优先级别
- POJ 3071 Football (概率DP)
- android material design 主题
- 74. Search a 2D Matrix
- ubuntu上mount移动硬盘
- 错误:unable to run app in simulator An error was encountered while runing
- Ping过程 原理 详解加图