Catching exception: divide by zero

后端 未结 8 1745
时光取名叫无心
时光取名叫无心 2020-11-22 16:23

The following code does not catch an exception, when I try to divide by 0. Do I need to throw an exception, or does the computer automatically throw one at runtime?

8条回答
  •  野性不改
    2020-11-22 17:00

    do i need to throw an exception or does the computer automatically throws one at runtime?

    Either you need to throw the exception yourself and catch it. e.g.

    try {
      //...
      throw int();
    }
    catch(int i) { }
    

    Or catch the exception which is thrown by your code.

    try {
        int *p = new int();
    }
    catch (std::bad_alloc e) {
        cerr << e.what();
    }
    

    In your case, I am not sure if is there any standard exception meant for divide by zero. If there is no such exception then you can use,

    catch(...) {  // catch 'any' exception
    }
    

提交回复
热议问题