VC除零异常(错误)捕获

// testFinally.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> using namespace std; #include <windows.h> std::string s; //本源码在VC2008+SP1 WindowsXP+SP3 下测试通过 by lee353086 void myFinally() { int i=2;//"int i",不需要析构所以可以放在这里 //注意"std::string s;"这行代码不能放在 //这里,因为s这个对象需要析构 //除0,非法指令、存取违例 等等对C++而言是 错误,而不是 异常,和 try-catch 无关 //所以这里得使用__try__except来捕获除零错误 __try { s="My Finally"; //throw s;//这里throw的s异常会被_tmain中的catch(std::string s)捕获,myFinally函数体剩余的代码将不会被执行 i = i/0; } //下面这行可以用用__except(1)来代替,这样就不需要包含#include <windows.h>这段代码 __except( GetExceptionCode()==EXCEPTION_INT_DIVIDE_BY_ZERO ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH ) { cout<<"got除零错误!"<<endl; } cout<<s.c_str()<<endl; } int _tmain(int argc, _TCHAR* argv[]) { cout<<"main begin"<<endl; try{ myFinally(); }catch(std::string s) { cout<<"got其它错误"<<endl; } cout<<"main end"<<endl; return 0; }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值