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?
You can just do assert(2 * i != i)
which will throw an assert. You can write your own exception class if you need something fancier.
setjmp
+ longjmp
https://stackoverflow.com/a/25601100/895245 mentioned the possibility or throwing a C++ exception from a signal handler, but Throwing an exception from within a signal handler mentions several caveats of that, so I would be very careful.
As another potentially dangerous possibility, you can also try to use the older C setjmp
+ longjmp
mechanism as shown at: C handle signal SIGFPE and continue execution
main.cpp
#include <csetjmp>
#include <csignal>
#include <cstring>
#include <iostream>
jmp_buf fpe;
void handler(int signum) {
longjmp(fpe, 1);
}
int main() {
volatile int i, j;
for(i = 0; i < 10; i++) {
struct sigaction act;
struct sigaction oldact;
memset(&act, 0, sizeof(act));
act.sa_handler = handler;
act.sa_flags = SA_NODEFER | SA_NOMASK;
sigaction(SIGFPE, &act, &oldact);
if (0 == setjmp(fpe)) {
std::cout << "before divide" << std::endl;
j = i / 0;
sigaction(SIGFPE, &oldact, &act);
} else {
std::cout << "after longjmp" << std::endl;
sigaction(SIGFPE, &oldact, &act);
}
}
return 0;
}
Compile and run:
g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main.out main.cpp
./main.out
Output:
i = 0
before divide
after longjmp
i = 1
before divide
after longjmp
i = 2
before divide
after longjmp
man longjmp
says that you can longjmp
from signal handlers, but with a few caveats:
POSIX.1-2008 Technical Corrigendum 2 adds longjmp() and siglongjmp() to the list of async-signal-safe functions. However, the standard recommends avoiding the use of these functions from signal handlers and goes on to point out that if these functions are called from a signal handler that interrupted a call to a non-async-signal-safe function (or some equivalent, such as the steps equivalent to exit(3) that occur upon a return from the initial call to main()), the behavior is undefined if the program subsequently makes a call to a non-async-signal-safe function. The only way of avoiding undefined behavior is to ensure one of the following:
After long jumping from the signal handler, the program does not call any non-async-signal-safe functions and does not return from the initial call to main().
Any signal whose handler performs a long jump must be blocked during every call to a non-async-signal-safe function and no non-async-signal-safe functions are called after returning from the initial call to main().
See also: Longjmp out of signal handler?
However Throwing an exception from within a signal handler mentions that this has further dangers with C++:
setjmp and longjmp aren't compatible with exceptions and RAII (ctors/dtors), though. :( You'll probably get resource leaks with this.
so you would have to be very very careful with that as well.
I guess the moral is that signal handlers are hard, and you should avoid them as much as possible unless you know exactly what you are doing.
Detect floating point zero division
It is also possible to detect floating point division by zero with a glibc call to:
#include <cfenv>
feenableexcept(FE_INVALID);
as shown at: What is the difference between quiet NaN and signaling NaN?
This makes it raises SIGFPE as well like the integer division by zero instead of just silently qnan and setting flags.
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
}
You need to check it yourself and throw an exception. Integer divide by zero is not an exception in standard C++.
Neither is floating point divide by zero but at least that has specific means for dealing with it.
The exceptions listed in the ISO standard are:
namespace std {
class logic_error;
class domain_error;
class invalid_argument;
class length_error;
class out_of_range;
class runtime_error;
class range_error;
class overflow_error;
class underflow_error;
}
and you could argue quite cogently that either overflow_error
(the infinity generated by IEEE754 floating point could be considered overflow) or domain_error
(it is a problem with the input value) would be ideal for indicating a divide by zero.
However, section 5.6
(of C++11
, though I don't think this has changed from the previous iteration) specifically states:
If the second operand of
/
or%
is zero, the behavior is undefined.
So, it could throw those (or any other) exceptions. It could also format your hard disk and laugh derisively :-)
If you wanted to implement such a beast, you could use something like intDivEx
in the following program (using the overflow variant):
#include <iostream>
#include <stdexcept>
// Integer division, catching divide by zero.
inline int intDivEx (int numerator, int denominator) {
if (denominator == 0)
throw std::overflow_error("Divide by zero exception");
return numerator / denominator;
}
int main (void) {
int i = 42;
try { i = intDivEx (10, 2); }
catch (std::overflow_error e) {
std::cout << e.what() << " -> ";
}
std::cout << i << std::endl;
try { i = intDivEx (10, 0); }
catch (std::overflow_error e) {
std::cout << e.what() << " -> ";
}
std::cout << i << std::endl;
return 0;
}
This outputs:
5
Divide by zero exception -> 5
and you can see it throws and catches the exception for the divide by zero case.
The %
equivalent is almost exactly the same:
// Integer remainder, catching divide by zero.
inline int intModEx (int numerator, int denominator) {
if (denominator == 0)
throw std::overflow_error("Divide by zero exception");
return numerator % denominator;
}
You need to throw the exception manually using throw
keyword.
Example:
#include <iostream>
using namespace std;
double division(int a, int b)
{
if( b == 0 )
{
throw "Division by zero condition!";
}
return (a/b);
}
int main ()
{
int x = 50;
int y = 0;
double z = 0;
try {
z = division(x, y);
cout << z << endl;
}catch (const char* msg) {
cerr << msg << endl;
}
return 0;
}
You should check if i = 0
and not divide then.
(Optionally after checking it you can throw an exception and handle it later).
More info at: http://www.cprogramming.com/tutorial/exceptions.html