Skip to main content

Command Palette

Search for a command to run...

Why Error Codes Are Better Than Exceptions

Updated
2 min read
A

I am a Student, who finds beauty in simple things. I like to teach sometimes.

When writing code, handling errors properly is super important. Two common ways to deal with errors are error codes and exceptions. While exceptions may seem fancy, error codes often work better, especially for performance, readability, and maintainability.

1. Error Codes Are Predictable

With error codes, you always know what to expect. The function returns a specific number (or an enum) that tells you if something went wrong. You don’t have to worry about unexpected exceptions suddenly stopping your program.

For example:

int result = openFile("data.txt");
if (result == FILE_NOT_FOUND) {
    printf("File not found!");
}

Here, we check for the error before doing anything else. No surprises!

2. Better Performance

Exceptions slow things down. Because handling an exception requires extra processing from the system, like collecting a stack trace and jumping out of the normal code flow. Error codes, on the other hand, are just simple values that the CPU can handle super fast.

If performance is key (like in gaming or embedded systems), error codes are the way to go.

3. Easier to Read & Understand

With error codes, you can see all possible outcomes in one place. Exceptions, however, can be thrown from deep inside a function, making it hard to track where the problem started.

Compare these two styles:

Using Error Codes:

int result = connectToServer();
if (result != SUCCESS) {
    printf("Connection failed!");
}

Using Exceptions:

try {
    connectToServer();
} catch (ConnectionException e) {
    printf("Connection failed!");
}

At first glance, both look fine. But what if connectToServer throws multiple exceptions from deep inside the code? Now, you have to track down every possible exception, which can be tricky.

4. No Hidden Control Flow

Exceptions jump around the code unexpectedly. If an exception is thrown inside a function and not caught properly, it might crash your entire application.

Error codes keep things simple—you know exactly where errors happen and how they are handled.

5. Works Well in All Languages

Not all programming languages support exceptions, but all of them support returning error codes. If you're working with C, Go, or even low-level systems programming, error codes are the standard.


Conclusion

Exceptions might seem like a convenient way to handle errors, but they introduce unpredictability, performance overhead, and hidden control flow issues. Error codes keep things simple, fast, and easy to debug. These are just my opinions. No need to take it on your organs specially heart and ass. Be chill. No language is superior. Use whatever gets the work done. Peace.

More from this blog

Aman Pathak

58 posts

Things I would speak if the person in front of me is me