Avoid catching broad exception types like Exception
and instead catch specific exceptions that you expect and can handle appropriately. When errors occur, they should be explicit rather than failing silently, and should include proper logging or re-raising when necessary.
Key principles:
except Exception:
clausesExample of what to avoid:
try:
last_parameters_msg.liveParameters.stiffnessFactor = last_parameters_dict['stiffnessFactor']
params_reader.put("LiveParameters", last_parameters_msg.to_bytes())
except Exception: # Too broad, fails silently
pass
Better approach:
try:
last_parameters_msg.liveParameters.stiffnessFactor = last_parameters_dict['stiffnessFactor']
params_reader.put("LiveParameters", last_parameters_msg.to_bytes())
except (json.JSONDecodeError, KeyError) as e: # Specific exceptions
cloudlog.warn(f"Failed to migrate cached params: {e}")
This approach makes code more maintainable by clearly documenting what can go wrong and ensuring failures are visible rather than hidden.
Enter the URL of a public GitHub repository