I agree that Clanmjc's example is poor |
I agree that the example is poor, but based on the posters assumption that if statements could be used just as exceptions were, made me think that the posters knowledge of how exceptions occurring at all was very "simple". So I used a poor, but so simple that a first year student could see how something bad could happen with that example. Of course you could use if statement in this case, but if you tried to open the file for writing and it was read only, or you tried to open the file from a service account that did not have write access to the file that is owned by some other account an exception would be thrown and no if, case statement, could handle this, the program would exit.
Here is a more concrete example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
class BaseOne
{
//....
}
class BaseTwo
{
//...
}
class DerivedTwo : public BaseTwo
{
//...
}
|
Later in the code this function takes a reference to the
BaseOne
class but then tries to cast to the
DerivedTwo
which inherits from
BaseTwo
, throws bad cast exception
1 2 3 4 5
|
void SomeFunctions(const BaseOne& obj)
{
dynamic_cast<const DerivedTwo &>(obj); //Throws bad_cast exception
}
|
The side effect of Line 3 in the function code block can only be handled through a catch.
Exceptions are used for runtime errors (errors that go beyond the scope of logical errors, exceptional, abnormal, extraordinary, heteromorphic, irregular errors, but they can be anticipated), conditional statements are used by 'logical errors' for lack of a better word.