ssuman
ssuman

Reputation: 1

How to handle exception in called function in c++

If I have to call a particular function in which devide by zero is happening. We cannot modify anything in called function. Only way to prevent is by doing some modifiaction in calling function. How t do that?

for ex:

//calling function

int func(5,1);

//called function

int func(int x,int y)
{
  y--;
 return(x/y); // here divide by zero will occur, but we cannot do any thing in 
              // called function
}

How to keep our application running instead of this exception ?

Upvotes: 0

Views: 513

Answers (4)

Andrew Tomazos
Andrew Tomazos

Reputation: 68618

Under Linux you can install a signal handler function for SIGFPE (with signal(2)) and within it throw an exception, and then compile your code with -fnon-call-exceptions.

Once that is done a divide by zero will cause an exception to be thrown.

For Windows there is some stuff mentioned here: Dealing with Floating Point exceptions

Upvotes: 1

Abhineet
Abhineet

Reputation: 6617

You can do this in the calling function:-

if(i == 0)
  cout<<" info::i is equal to zero";
else
  func(5,i);

Upvotes: 0

Alok Save
Alok Save

Reputation: 206518

There are two ways to handle this:

Enforce Parameter checking:

In the calling code you should check the divisor.

if(y != 0)
    func(x,y);
else
  //Some log or error handling

OR

Throw an Exception:

An Integer divided by zero is not an standard C++ exception. So You just cannot rely on an exception being thrown implicitly. An particular compiler might map the divide by zero to some kind of an exception(You will need to check the compiler documentation for this), if so you can catch that particular exception. However, note that this is not portable behavior and will not work for all compilers.

So given the above the best you can do is to check the error condition(divisor equals zero) yourself and throw an exception explicitly say of the type std::runtime_error.


Either case your code should document the behavior appropriately, In first case your code should document valid supported values while in second it should specify what exceptions can be thrown.

Upvotes: 3

Bj&#246;rn Pollex
Bj&#246;rn Pollex

Reputation: 76788

In general you can:

  1. Check the parameters before calling the function to make sure they are valid. The function should include some documentation that specifies valid ranges of input.
  2. Catch the exception. (This is not applicable in this case, but in general it is an option).

Upvotes: 0

Related Questions