Thursday, July 25, 2013

Use exceptions, not error codes

Benefits of handling errors with exceptions instead of error codes [Advantages of Exceptions] :

Normal program flow and error handling can be visually separated which makes code reading easier. Easier to read means less bugs and peace of mind.

Let's say have a main method which calls 3 other methods. With the error code strategy, the three methods return true if everything is ok and false if there is an error. You want to exit your main method as soon as an error occurs to prevent error propagation. Our code has to look like this:

public void mainMethod() {
...
if ( f1() ) {
...
if ( f2() ) {
...
if ( f3() ) {
...
} else {
//Handle error in f3()
}
} else {
//Handle error in f2()
}
} else {
//Handle error in f1()
}
}

As you see, we have nested if statements and error handling is dispersed among normal flow. If the three methods returned multiple error codes instead of just false, it would look a lot messier.

If our three methods threw exceptions instead of returning error codes, our code would look like this:

public void myMainMethod() {
try {
...
f1();
...
f2();
...
f3();
...
} catch (F1Exception e) {
//Handle error in f1()
} catch (F2Exception e) {
//Handle error in f2()
} catch (F3Exception e) {
//Handle error in f3()
}
}

With the exception method, we have clean separation between normal flow and error handling.

The Java compiler forces you to handle all exceptions, otherwise it won't compile. With error codes you don't get that support because the compiler won't tell you if you have handled all error cases or not. You have to do it manually, which becomes difficult when you have many error cases to handle.

No comments: