Exeptions exists to separate normal program flow (what the program is designed to do) from the error handling flow (how program is trying to recover from an exceptional situation).
This makes code more clear and easier to maintain.
Consider two code sniplets:
try:
do1() # this is obvoiusly a normal
do2() # program flow
except:
oups() # this is exception handling code
Compared to this one:
if foo():
thing1() # is this part of normal program flow?
else:
thing2() # or maybe this one? Or both? When?
Of course, exception handling can be used to prevent program from crashing by:
try { // very bad code
my();
whole();
ugly();
application();
here();
} catch (Throwable t) {
// pretend it's ok
}
but this is not the reason for the exceptions in modern programming languages.
You can also use while
and break
instead of if
but this is not what while
and break
are for.