Home > Back-end >  What's the difference between if/else and try catch(exception)?
What's the difference between if/else and try catch(exception)?

Time:01-06

for example this code I can do it like this, this is simple if / else

if (age>=18)
cout << "Access granted - you are old enough.";
else {
    cout << "Access denied - You must be at least 18 years old.\n";
    cout << "Age is: " << age;  
}

and this is the "same code" with exception

try {
  int age = 15;
  if (age >= 18) {
    cout << "Access granted - you are old enough.";
  } else {
    throw (age);
  }
}
catch (int myNum) {
  cout << "Access denied - You must be at least 18 years old.\n";
  cout << "Age is: " << myNum;
}

why would I use exception if I can do the same code without exception?

CodePudding user response:

Exceptions should very rarely be used to control the "normal" flow of a program. They are supposed to be exceptions to the normal flow.

Example:

try {
    age = get_age();
    name = get_name();
    shoe_size = get_shoe_size();
    ...
    ... work with the data gathered without checking that each function succeeded ...
}
catch(...) {
    one of the functions failed to collect the data needed
}

CodePudding user response:

why would I use exception if I can do the same code without exception?

You typically wouldn't throw if you could do the same without it. Your code is a good example of a case where you shouldn't throw.

You would typically throw in cases where you cannot elegantly do same code without throwing.

  •  Tags:  
  • Related