c++ - 我的 try catch 零除法有问题吗?

标签 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>

如你所见,这里没有发生任何事情

最佳答案

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

关于c++ - 我的 try catch 零除法有问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56094256/

相关文章:

带有从迭代器获取的指针参数的 C++ 模板函数给出错误

c++ - 未定义对构造函数的引用,当我明确拥有它时 "type out"

c++ - 解析C头文件生成文件

c++ - 子序列和模的乘积

c++ - 带有随机指针的链表的深拷贝

c++ - 当包含类头时,为什么我的数组在 main 中未定义?

c++ - 行号 : Any way to use __LINE__ to return line number of input file?

c++ - 当客户端连接很少且间隔很远时,服务器监听的明智方法是什么(在Linux上使用套接字编程)

c++ - 使函数内联会影响绑定(bind)到其参数的临时对象的生命周期吗?

c++ - AES 加密/解密文本