在代码中捕获异常

编程入门 行业动态 更新时间:2024-10-23 14:28:38
本文介绍了在代码中捕获异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试这段代码来检查是否捕获了除零异常:

I was trying this piece of code to check whether the divide by zero exception is being caught:

int main(int argc, char* argv[]) { try { //Divide by zero int k = 0; int j = 8/k; } catch (...) { std::cout<<"Caught exception\n"; } return 0; }

当我使用VC6进行编译时,执行catch处理程序,输出为捕获异常。但是,当我使用VS2008进行编译时,该程序崩溃了,没有执行catch块。造成差异的原因可能是什么?

When I complied this using VC6, the catch handler was executed and the output was "Caught exception". However, when I compiled this using VS2008, the program crashed without executing the catch block. What could be the reason for the difference?

推荐答案

在项目->属性->配置属性-> c下启用结构化异常处理/ c ++->代码生成->启用c ++异常。

Enable structured exception handling under project -> properties -> configuration properties -> c/c++ -> code generation -> enable c++ exceptions.

请尝试一下。理想情况下,使用一个检查异常代码的过滤器,然后在希望捕获时返回常量信令。我在这里略过了,但我建议您在此处作为过滤器示例。

Use a try except. Ideally with a filter that checks the exception code then returns the constant signalling if it would like to catch. I have skipped that out here but I recommend you see here for examples of the filter.

#include <iostream> #include <windows.h> int main(int argc, char* argv[]) { __try { //Divide by zero int k = 0; int j = 8/k; } __except(EXCEPTION_EXECUTE_HANDLER) { if(GetExceptionCode()==EXCEPTION_INT_DIVIDE_BY_ZERO) std::cout << "Caught int divison exception\n"; else std::cout << "Caught exception\n"; system("pause"); } return 0; }

更多推荐

在代码中捕获异常

本文发布于:2023-11-15 14:02:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1595085.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:异常   代码

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!