throw catch try
来源:互联网 发布:addictive drums mac 编辑:程序博客网 时间:2024/05/22 15:02
C++学的太少,一天连发三篇日志,记录C++学习的基础知识。今天师兄让我使用catch try处理程序的异常,但是不会,有点丢人,只能慢慢学习了。
throw就是抛出异常,通常会有条件,如果某个条件出现了,那么throw,抛出异常,throw后面是某一类的对象。
try里面是极有可能出现异常的代码,如果满足了触发throw的条件,就会throw,然后catch就是紧着着处理这个异常,通常catch后紧接着某一类。
#include<iostream> //包含头文件#include<stdlib.h>using namespace std;double fuc(double x, double y) //定义函数{if(y==0){ throw y; //除数为0,抛出异常} return x/y; //否则返回两个数的商}void main(){double res;try //定义异常{res=fuc(4,0);res=fuc(2,3);cout<<"The result of x/y is : "<<res<<endl; //出现异常}catch(double) //捕获并处理异常{ cerr<<"error of dividing zero.\n"; exit(1); //异常退出程序}}上面的程序,当除数为0时,会触发异常处理,那么结果如下图所示:
可以看到,输出结果是一段字符串,有点像跳转语句。后面的fun(2,3)也没有执行。
#include <iostream>using namespace std;class ExceptionClass{char* name;public:ExceptionClass( char* name="default name") {cout<<"Construct "<<name<<endl;this->name = name;}~ExceptionClass(){cout<<"Destruct "<<name<<endl;}void mythrow(){//这里才是真正的throw,抛出一个对象。throw ExceptionClass("my throw"); }};void main(){ExceptionClass e("Test");try{e.mythrow();} catch(...)//其它错误异常{cout<<"*********"<<endl;}}
catch(...)是为了防止某些想不到的异常,catch 后面紧跟着是类的名称,即使声明了某一对象,也不会分配空间。直接上结果:
- try...catch...throw
- try catch throw用法
- catch,try,throw
- try catch throw用法
- try catch throw用法
- try,catch,throw
- try catch throw 使用
- try catch throw用法
- try catch throw用法
- try throw catch
- try catch throw用法
- JavaScript try...catch throw
- C++ try/catch/throw
- try catch throw用法
- throw catch try
- try catch throw
- JavaScript try-catch-throw
- C# try catch throw
- C++ 函数映射使用讲解
- 终于开博啦!
- Android动态刷新listview中的数据
- hdu1248
- Jquery
- throw catch try
- iOS开发资源汇总
- 说说Java中的枚举(小姐)
- using与namespace
- 文件_图片的无刷新上传
- NOJ [F] 懒惰的风纪委Elaine 求一堆数能组成多少个数小于等于n
- N皇后位运算版
- 忙碌起来
- 杭电1492-The number of divisors(约数) about Humble Numbers