Reputation: 1
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
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
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
Reputation: 206518
There are two ways to handle this:
In the calling code you should check the divisor.
if(y != 0)
func(x,y);
else
//Some log or error handling
OR
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
Reputation: 76788
In general you can:
Upvotes: 0