Exception Handling and Math Errors

J

Joe Hesse

What do I have to do to the following program to catch the runtime error?
Many thanks,
Joe Hesse

------------------------------------------------
#include <iostream>
#include <stdexcept>
using namespace std;

void f()
{
int x = 1, y = 0, z;
z = x/y; // divide by zero
}

int main()
{
try
{
f(); // function has a runtime error
}
catch(const runtime_error &re)
{
cerr << re.what() << "\n";
}
catch(...)
{
cerr << "Caught ..." << "\n";
}

return 0;
}

------------------------------------------------
 
A

Alf P. Steinbach

* "Joe Hesse said:
What do I have to do to the following program to catch the runtime error?

AFAIK there's no fully platform-independent way to do that. One "nearly"
platform-independent way is to use a C SIGFPE signal (see 'signal') to set
a flag somewhere, which you can then check after the arithmetic. But in
practice this also involves platform-dependent code, so you might as well
go all the way in that direction -- just try to wrap it nicely up.

Note: you can use std::numeric_limits<double> to check what kind of support
your C++ implementation has for various floating point functionality.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top