简体   繁体   中英

Is there something wrong with my try catch zero division?

I tried to make simple program to catch and error by making function that divided an int to zero but i don't see the error neither the correct output

#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> 

As you can see nothing happens here

Doing

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

the code after is not executed (undefined behavior), probably you do not wanted to divide by zero using '/' but using your function ;-)

putting z = x / y; in comment you get your expected behavior :

#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;
}

Compilation and execution :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM