DEV Community

Cover image for Lesson 5 – Handling Errors and Exceptions in Payroll Systems
Daniel Azevedo
Daniel Azevedo

Posted on

Lesson 5 – Handling Errors and Exceptions in Payroll Systems

Welcome back to our Python from 0 to Hero series! In the last lesson, we learned how to read and write files, which is a vital skill for any real-world HR or payroll system. However, when you work with external data like files, user input, or API responses, things don't always go as expected.

This brings us to an essential aspect of programming: error handling. Errors are inevitable in software development, but knowing how to handle them gracefully will make your Python applications more reliable and professional.

In this lesson, we’ll cover:

  1. Common types of errors in Python.
  2. How to use try-except blocks to handle exceptions.
  3. Practical examples for handling errors in payroll systems, such as missing data and invalid inputs.

By the end of this lesson, you’ll be able to write more robust code that can handle unexpected situations and keep your HR systems running smoothly.


1. Common Errors in Python

Before we dive into handling errors, let’s look at some common errors that you might encounter in Python, especially when working with employee data:

  • SyntaxError: Happens when there’s an issue with the structure of your code.

    print("Employee Data)
    

    Output:

    SyntaxError: EOL while scanning string literal
    
  • FileNotFoundError: Occurs when the file you are trying to open doesn’t exist.

    with open("nonexistent_file.txt", "r") as file:
        data = file.read()
    

    Output:

    FileNotFoundError: [Errno 2] No such file or directory: 'nonexistent_file.txt'
    
  • KeyError: Raised when trying to access a key in a dictionary that doesn’t exist.

    employees = {101: "Alice", 102: "Bob"}
    print(employees[103])
    

    Output:

    KeyError: 103
    
  • ValueError: Raised when a function receives a value of the correct type but inappropriate for the operation.

    age = int("twenty-five")
    

    Output:

    ValueError: invalid literal for int() with base 10: 'twenty-five'
    

These are just a few examples, but there are many other types of errors that can occur when working with files, dictionaries, or user input. Luckily, Python gives us tools to catch and handle these errors so that they don’t crash your programs.


2. Using Try-Except for Error Handling

The most common way to handle errors in Python is by using a try-except block. Let’s see how it works:

Basic Structure of Try-Except

try:
    # Code that might raise an error
    risky_operation()
except SomeError as e:
    # Handle the error
    print(f"An error occurred: {e}")
Enter fullscreen mode Exit fullscreen mode
  • The try block contains code that could potentially raise an error.
  • The except block handles the error and prevents your program from crashing.

Let’s apply this to a real-world HR example: handling a missing employee file.

Example: Handling FileNotFoundError

try:
    with open("employee_data.txt", "r") as file:
        data = file.read()
        print(data)
except FileNotFoundError as e:
    print(f"Error: The file was not found. Details: {e}")
Enter fullscreen mode Exit fullscreen mode

In this example, if the file doesn’t exist, Python will catch the FileNotFoundError and print a user-friendly error message instead of crashing the program.


3. Handling Multiple Exceptions

Sometimes, multiple types of errors can occur, and you might want to handle them differently. You can use multiple except blocks to catch different exceptions.

Example: Handling Multiple Error Types

Let’s modify our employee salary update system to handle both file errors and key errors when updating employee records.

employees = {
    101: {"name": "Alice", "salary": 5000},
    102: {"name": "Bob", "salary": 4000}
}

try:
    # Trying to read employee data from a file
    with open("employee_data.txt", "r") as file:
        data = file.read()

    # Update salary for a non-existent employee
    emp_id = 103
    employees[emp_id]["salary"] = 4500

except FileNotFoundError:
    print("Error: The employee data file does not exist.")
except KeyError as e:
    print(f"Error: Employee ID {e} not found in the system.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")
Enter fullscreen mode Exit fullscreen mode

How It Works:

  1. If the file employee_data.txt is missing, the program will display an error message for a missing file.
  2. If you try to update the salary for an employee that doesn’t exist (ID 103), it will catch the KeyError and print a message about the missing employee.
  3. The general except block catches any other unexpected errors.

This ensures that even if multiple things go wrong, your program can handle each situation properly.


4. Validating User Input in Payroll Systems

Another common scenario where error handling is important is when validating user input. For example, when processing payroll data, you need to ensure that all inputs are valid, such as numeric values for salaries and hours worked.

Example: Validating Numeric Input

Let’s create a script that asks for an employee’s worked hours and validates that the input is a valid number.

def get_worked_hours():
    while True:
        try:
            hours = float(input("Enter the number of hours worked: "))
            if hours < 0:
                raise ValueError("Hours worked cannot be negative.")
            return hours
        except ValueError as e:
            print(f"Invalid input: {e}. Please enter a valid number.")

# Example usage
worked_hours = get_worked_hours()
print(f"Hours worked: {worked_hours}")
Enter fullscreen mode Exit fullscreen mode

How It Works:

  1. The get_worked_hours() function continuously asks the user to input a valid number.
  2. If the user enters anything other than a positive number, it raises a ValueError with a custom message and prompts them again.
  3. This loop continues until a valid number is entered.

Example Output:

Enter the number of hours worked: -5
Invalid input: Hours worked cannot be negative. Please enter a valid number.
Enter the number of hours worked: abc
Invalid input: could not convert string to float: 'abc'. Please enter a valid number.
Enter the number of hours worked: 40
Hours worked: 40.0
Enter fullscreen mode Exit fullscreen mode

This is an excellent way to ensure that user input is always valid, preventing errors in later parts of your payroll calculations.


5. Raising Custom Exceptions

Sometimes, you may want to raise your own exceptions when certain conditions are met. This is useful for enforcing business rules in your payroll system.

Example: Enforcing Salary Limits

Let’s say your company has a rule that salaries cannot exceed $10,000. If someone tries to set a salary higher than that, we’ll raise a custom exception.

class SalaryTooHighError(Exception):
    pass

def set_salary(emp_id, salary):
    if salary > 10000:
        raise SalaryTooHighError(f"Error: Salary for employee {emp_id} exceeds the limit.")
    employees[emp_id]["salary"] = salary

# Employee dictionary
employees = {
    101: {"name": "Alice", "salary": 5000},
    102: {"name": "Bob", "salary": 4000}
}

try:
    # Attempt to set an excessively high salary
    set_salary(101, 15000)
except SalaryTooHighError as e:
    print(e)
Enter fullscreen mode Exit fullscreen mode

How It Works:

  1. We define a custom exception SalaryTooHighError.
  2. In the set_salary() function, we check if the salary exceeds $10,000. If it does, we raise our custom exception.
  3. In the try block, we catch this custom exception and display an appropriate message.

Example Output:

Error: Salary for employee 101 exceeds the limit.
Enter fullscreen mode Exit fullscreen mode

This helps you enforce specific business rules and make your payroll system more robust.


Conclusion

In this lesson, we covered the essentials of error and exception handling in Python:

  • Common error types like FileNotFoundError and KeyError.
  • Using try-except blocks to catch and handle errors.
  • Handling multiple exceptions and validating user input.
  • Raising custom exceptions to enforce business rules.

These skills are critical for building reliable and user-friendly HR systems. In the next lesson, we’ll dive into working with external libraries, which will allow you to expand your Python capabilities even further.

As always, feel free to ask questions or share your thoughts in the comments. Happy coding!!!

Top comments (0)