exception handling

1
2
3
4
if( num2 == 0)
   cout << "Error: Dividing By Zero" << endl;
else
   cout << num1 / num2;


this code "test if he dividing by zero" work correctly
& continue executing the rest of code
what's the benefit of exception handling here
why is used in code like this instead of "if"
if I understand your question, the difference is to use the exclusive conditions:
practically the if / else statement is equivalent to the condition 'xor'. then the second part of the code is only used if the first is false.

using two if statements in a row, make the code inside the if statement, independent of each other. is almost as if I used the logical condition 'or';
then the two statements can be true at the same time and run concurrently. therefore (number1 / number2) would also performed (if num2 == 0)
Last edited on
I know what this code is mean

I need to know what the difference bitween this & another code use exception handling
why they use "try catch" in code like this ?

what's the benefit ?
The benefit of exception handling is that you can put all of your error handling in one place and you don't need to continue the calculation.
1
2
3
4
if (num2 == 0)
  throw std::string("Error: Dividing by zero");

result = num1/num2;


In your example, let's say that you are calculating speed:
speed = distance/time;

Now we are probably going to use speed later in the code, but if time is 0, then it's completely invalid! By throwing an exception, we are ensuring that we get the heck out of the entire function and returning to an area dedicated to error handling.
1
2
3
4
5
6
7
8
9
10
11
12
int foo( int a, int b )
{
  return a / b;
}

int bar( int a, int b, int d[10] )
{
  return d[ 7 + foo( a, b - 1 ) ];
}
...
int c = bar( 42, 1 array );
// use c 

How does foo tell to bar that things went wrong? That the value returned is invalid?
How does bar tell the using code that things went wrong? What if there should be no return value on error?

Yes, you can test, but how does a function report the error?
It could use a reference parameter.
1
2
3
void gaz( bool & ok );
...
bool test; gaz( test ); if ( test ) ...

It could use a global variable.
1
2
... fscanf(...);
// check the errno 

Or, it can throw an exception.

Exception is thus closer to writing to a global variable that an error has occurred; no-one in the call stack needs to look at it if they don't care, nor explicitly pass it on. However, if no-one catches it, then the program stops.

I don't make exceptions, so I might have been wrong on details.
Topic archived. No new replies allowed.