0

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

bruno
  • 32,421
  • 7
  • 25
  • 37

1 Answers1

2

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
bruno
  • 32,421
  • 7
  • 25
  • 37
  • 1
    It's *undefined behavior* which precedes the well-defined `division` call. It still may appear to "work". – LogicStuff May 11 '19 at 21:07
  • @LogicStuff yes, in my case `z = x/ y;` writes `Exception en point flottant` then stop the execution (sorry for french message ^^) – bruno May 11 '19 at 21:11
  • The English version is `Floating poing exception` (the message for `SIGFPE`). – melpomene May 11 '19 at 21:13
  • @melpomene hehe yes sure, I put the French version I get mainly for joke, the translation is funny because in French we use _comma_ (in French _virgule_) rather than _point_, so _exception en virgule flottante_ – bruno May 11 '19 at 21:18