捕获int的异常除以0 [英] exception catching for int divided by 0

查看:96
本文介绍了捕获int的异常除以0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我正在尝试使用C ++编写的简单异常程序,如下所示:-

Recently i was trying a simple exception program in C++ which goes like this:-

#include <iostream>
#include <exception>
#include <stdexcept>
using namespace std;
int main()
{
    int x=5, y=0;
    try
    {
       int z=x/y;
       cout<<"z="<<z;
    }
    catch (exception& e)
    {
       cout<<"exception caught: "<<e.what();
    }
    return 0;
}

为什么这里没有异常?代码有什么问题?
我也想知道为什么需要& 来捕获异常?

Why is no exception thrown here ? What is wrong in the code ? Also I would like to know why the & is required to catch exception ?

推荐答案

在标准C ++中,除以零的任何整数都不是例外。

Any integer when divided by zero is not an exception in standard C++.

C ++ 5.6节指出:

The section 5.6 of C++ states:


如果/或%的第二个操作数为零,则行为未定义。

If the second operand of / or % is zero, the behavior is undefined.

您可能还会发现阅读以下内容很有趣:

You may also find it interesting to read this:


Stroustrup在 C ++的设计和演变中说( Addison Wesley,1994年,
),低级事件,例如算术溢出和除以
零,被假定为由专用的较低级机制
处理,而不是由异常处理。这使C ++在算术方面能够与
其他语言的行为相匹配。它还避免了在
事件(例如被零除)是异步的,高度流水线的体系结构中发生的
问题。

Stroustrup says, in "The Design and Evolution of C++" (Addison Wesley, 1994), "low-level events, such as arithmetic overflows and divide by zero, are assumed to be handled by a dedicated lower-level mechanism rather than by exceptions. This enables C++ to match the behaviour of other languages when it comes to arithmetic. It also avoids the problems that occur on heavily pipelined architectures where events such as divide by zero are asynchronous."`

这篇关于捕获int的异常除以0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆