Clean Code with Exception

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:

  1. Calculate salary for employees -> my task
  2. Transfer salary to employees -> teammate’s task
  3. 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? ;)

1
2
3
public int calcSalary(int workingDay, int salaryPerDay) {
    return workingDay * salaryPerDay;
}

After sending it to the boss for review, I got scolded! What if workingDay or salaryPerDay is negative?

I quickly replied: “The caller should handle that!”
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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class SalaryResult {
    private int salary = 0;
    private int errorCode = 0;

    // getters and setters
}

public SalaryResult calcSalary(int workingDay, int salaryPerDay) {
    SalaryResult res = new SalaryResult();
    
    if (workingDay < 0) {
        res.setErrorCode(1);
    }

    if (salaryPerDay < 0) {
        res.setErrorCode(2);
    }

    res.setSalary(workingDay * salaryPerDay);
    
    return res;
}

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:

  1. Method signature must be explicit and intuitive at a glance
  2. Provide the caller with detailed error information
  3. 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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public int calcSalary(int workingDay, int salaryPerDay) throws Exception {

    if (workingDay < 0)
        throw new Exception("WorkingDay less than zero");

    if (salaryPerDay < 0)
       throw new Exception("SalaryPerDay less than zero");

    return workingDay * salaryPerDay;
}

Now by adding throws Exception and passing descriptive messages when throwing an exception, everything becomes clean and straightforward.

Here is the demo program:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class Salary {
    public static void main(String[] args) {

        try {
            int salary = calcSalary(21, 1_000_000);
            System.out.println("Salary: " + salary);

            // bla bla ble...
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    public static int calcSalary(int workingDay, int salaryPerDay) throws Exception {

        if (workingDay < 0)
            throw new Exception("WorkingDay less than zero");

        if (salaryPerDay < 0)
            throw new Exception("SalaryPerDay less than zero");

        return workingDay * salaryPerDay;
    }
}

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)
updatedupdated2026-09-052026-09-05
Load Comments?