Good Code Practices

Exception

Bad Practice

try:
    some logic
except Exception as e:
    self.logger.error(f"An error occurred: {e}. Type: {type(e).__name__}")
Python

Recommended (Good Practice)

Way 1

try:
    some logic
except IndexError as e:
    self.logger.error(f"IndexError: The list `ind_cert` is empty or the index is out of range. Error details: {e}")
except KeyError as e:
    self.logger.error(f"KeyError: The key 'Certification' is missing in the dictionary. Error details: {e}")
except Exception as e:
    self.logger.error(f"An error occurred: {e}. Type: {type(e).__name__}")
    raise  # Re-raises the exception after logging
    
Python

Way 2

try:
    some logic
except (IndexError,KeyError) as e:
    self.logger.error(f"Error: {e}")
Python

Catching a too general Exception is generally considered a bad practice because:

  • It hides real errors that you didn’t anticipate.
  • It can swallow important debugging information.
  • It can break flow control unintentionally by catching exceptions you don’t expect.

Idea Doc String format

def calculate_speed(distance: float, time: float) -> float:
    """
    Calculates the speed given distance and time.

    Args:
        distance (float): The distance traveled (in kilometers).
        time (float): The time taken (in hours).

    Returns:
        float: The speed in kilometers per hour.

    Raises:
        ZeroDivisionError: If `time` is zero.
    """
    
    #some logic 
    
Python

Leave a Comment