When I first started learning Java, the thing that frustrated me most was Exception. Every little thing seemed to demand a try/catch block (I’ll write a more detailed post on this later) and made my code look dreadful. But after spending time understanding it, I realized that exceptions are actually quite neat in programming.
Why? Read on! :v
Suppose our team receives a requirement from the boss to write a program that calculates and transfers salaries to company employees. From this requirement, our boss breaks it down into 3 tasks:
- Calculate salary for employees -> my task
- Transfer salary to employees -> teammate’s task
- Coordinate salary calculation and transfer -> boss’s task
The input parameters are the number of working days in the month and the daily salary rate. Seems super simple, right? ;)
| |
After sending it to the boss for review, I got scolded! What if workingDay or salaryPerDay is negative?
He countered: “I’m the caller here, you must validate your own inputs! Don’t trust me too much.” He said with a mysterious smile :~
So I reluctantly sat down to rewrite it :(.
From the boss’s requirement, we need to return information so he knows when the input data is invalid, what the specific error is, and the salary result if there are no errors. Here is where the problem starts. The method signature used to be clear and intuitive at a glance. Now, to let the caller know whether the passed parameters are valid, I returned a class containing the salary and an error code, where error code 0 means no error:
| |
The boss reviewed it and asked for changes again. The reason was that his job is coordinating calculation and transfer. Handling error codes meant he had to map error codes to display messages to the user. He said: “It’s not my business.” WTF x2 ;))
So I needed a way to satisfy all of these requirements:
- Method signature must be explicit and intuitive at a glance
- Provide the caller with detailed error information
- Break the execution flow when an error occurs
After some research, I found that this exact problem is very common and can be solved elegantly using Exception:
| |
Now by adding throws Exception and passing descriptive messages when throwing an exception, everything becomes clean and straightforward.
Here is the demo program:
| |
You can try changing workingDay or salaryPerDay to negative numbers to see the result!
Conclusion: By using Exception, we can:
- Keep method signatures clear and easy to understand
- Return rich error information (when needed) by using custom Exceptions (I will have a dedicated post on this)
- Make external control code cleaner by separating business logic from error handling (I will also cover this in an upcoming post)