Errors and Exceptions
Errors and exceptions are bane of any developer. However, these are two different things. Simply put:
Error — Damn! Something is wrong, causing problem, can not be recovered, stop doing whatever you are doing…
Exception — Ah! This could have been avoided, we can probably handle it and move on…
I have been working with JavaScript, PHP, Java and sometimes with Python. All of these handle errors and exceptions differently. Let’s take a look.
Errors
JavaScript doesn’t differentiate between errors and exceptions. True to JavaScript’s nature, both errors and exceptions are objects. If you look at MDN it says
Error objects are thrown when runtime errors occur. The Error object can also be used as a base object for user-defined exceptions.
Let’s temporarily set aside modern development tools and consider the following code:
console.log("Hello World!");
I am a piece of JavaScript code;
Running this will throw the following error in the browser JavaScript console:
Uncaught SyntaxError: Unexpected identifier 'am'
In Node.js, the error would look like this:
I am a piece of JavaScript code;
^^
Uncaught SyntaxError: Unexpected identifier
This is a SyntaxError
. Syntax errors will halt the program in any language. In fact, Java will not even compile due to syntax errors. Thankfully, modern IDEs will warn you about syntax errors before you deploy your code. If you’re still working on your code, you can configure your version control system to check for syntax errors. In any case, syntax errors are largely avoidable with modern tooling and proper attention to detail.
Some fatal conditions are often not caught by your IDE. Examples include:
- Resource exhaustion
- Stack over flow
- Calling methods or functions that aren’t available due to library linkage errors
- Issues with the underlying engine, such as the JVM or V8
PHP allows you to create custom error handler functions. However, these do not handle fatal errors, such as syntax errors. PHP also enables you to register a shutdown function to handle errors to some extent. This combination provides some control over error handling. You can explore error and exception handling in Laravel for more details.
In Java, the JVM will throw an error and leave you to resolve it. You’ll need to dig into your toolbox and fix the issue manually.
Exceptions
Every number can be divided by another number — except for zero. Dividing a number by zero is undefined and represents an exception.
Consider this scenario: Your program is performing computations, and it may encounter a “divide by zero” situation. This is a typical example of an exception. You can handle such exceptions using try
, catch
, and finally
blocks. Here’s an example in Java:
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Caught an exception: " + e.getMessage());
} finally {
return 42;//The Answer to the Ultimate Question of Life, The Universe, and Everything
}
JavaScript, PHP, and Java all allow you to create custom exception classes or objects. These custom exceptions usually extend the main error or exception class of the respective language to offer specialized error-handling functionality. It’s advisable to use these custom exception mechanisms rather than relying on the default Exception
(or Error
in JavaScript) class. Custom exceptions provide more control and clarity when managing errors.
Handling errors and exceptions
All programs should log errors and exceptions using appropriate logging libraries. In my Node.js projects, I utilize such libraries for effective error tracking. Spring Boot and Laravel also offer strong logging mechanisms. Logging must be a core component of every project, with logs forwarded to a log analysis platform for monitoring and alerting. I have implemented variations of the ELK stack (Elasticsearch, Logstash, Kibana) to build alerting systems. For instance, exceptions during a user’s checkout process require immediate action, while issues like a user being unable to view a five-year-old order can be prioritized lower. At a leadership level, tracking the number of errors and the speed of resolution has been valuable in identifying top-performing developers. In case you are not logging, I highly recommend reading this article from 12 factor app.
In conclusion, effective error and exception handling is crucial for building robust and reliable applications. By understanding the differences between errors and exceptions and using the appropriate tools and techniques in your programming language, you can manage issues more efficiently. Whether you’re using custom exceptions in JavaScript, PHP, or Java, or leveraging modern development tools, good error handling practices not only prevent crashes but also enhance the maintainability and scalability of your projects. Always prioritize error logging, detection, and resolution to ensure a smoother user experience and a more resilient codebase.