我的尝试捕捉零除法有什么问题吗?

时间:2019-05-11 21:03:18

标签: c++

我试图通过制作将int分为零的函数来制作一个简单的程序来捕获并出错,但是我既没有看到错误也没有正确的输出

#include <iostream>

constexpr double division(int a, int b){
    if(b == 0)
        throw "Cannot be divides by  zero";
    return (a / b);
}


int main(){
    int x {50};
    int y {0};
    int z {0};
    z = x / y;
    try{
        z = division(x ,y);
        std::cout << z << std::endl;
    }catch (const char* msg) {
     std::cerr << msg << std::endl;
    }
    return 0;
}
 C:\Users\Tungki\Desktop\c>g++ jj.cc
 C:\Users\Tungki\Desktop\c>a
 C:\Users\Tungki\Desktop\c>

如您所见,这里什么也没发生

1 个答案:

答案 0 :(得分:2)

int x {50};
int y {0};
int z {0};
z = x / y; <<<<<<<<<<< divide by 0

之后的代码未执行(未定义的行为),可能您不想使用'/'除以零,而是使用函数;-)

在评论中加入z = x / y;,您将获得预期的行为:

#include <iostream>

constexpr double division(int a, int b){
    if(b == 0)
        throw "Cannot be divides by  zero";
    return (a / b);
}


int main(){
    int x {50};
    int y {0};
    int z {0};
    // z = x / y;
    try{
        z = division(x ,y);
        std::cout << z << std::endl;
    }catch (const char* msg) {
     std::cerr << msg << std::endl;
    }
    return 0;
}

编译和执行:

pi@raspberrypi:/tmp $ g++ -pedantic -Wall -Wextra d.cc
pi@raspberrypi:/tmp $ ./a.out
Cannot be divides by  zero