Exception Handling and Math Errors

Discussion in 'C++' started by Joe Hesse, Apr 13, 2004.

  1. Joe Hesse

    Joe Hesse Guest

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

    ------------------------------------------------
    Joe Hesse, Apr 13, 2004
    #1
    1. Advertising

  2. * "Joe Hesse" <> schriebt:
    >
    > 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.

    --
    A: Because it messes up the order in which people normally read text.
    Q: Why is top-posting such a bad thing?
    A: Top-posting.
    Q: What is the most annoying thing on usenet and in e-mail?
    Alf P. Steinbach, Apr 13, 2004
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Mark Healey
    Replies:
    7
    Views:
    1,451
    Tim Prince
    May 22, 2006
  2. Philipp
    Replies:
    9
    Views:
    1,088
    Mark Space
    Jul 23, 2008
  3. Martin DeMello

    Math::Infinity and Math::NaN

    Martin DeMello, Apr 29, 2005, in forum: Ruby
    Replies:
    4
    Views:
    113
    Florian GroƟ
    Apr 29, 2005
  4. Phrogz
    Replies:
    8
    Views:
    265
    Morton Goldberg
    Feb 8, 2007
  5. VK
    Replies:
    15
    Views:
    1,110
    Dr J R Stockton
    May 2, 2010
Loading...

Share This Page