如何在Python中使用try-except处理除零错误(面向编程新手)
Hey there! Let's walk through how to handle division-by-zero errors in your Python code using try-except blocks. Looking at your code, there are a few spots where division could fail if the denominator is zero—let's fix those step by step.
When you divide by zero in Python, it throws a ZeroDivisionError—that's the specific exception we need to catch. Instead of letting your code crash, we can wrap risky calculations in try-except to handle these cases gracefully.
Your current code uses dictionary comprehensions, which are concise but make inline error handling tricky. A cleaner approach is to either:
- Extract the calculation logic into helper functions with built-in error handling, or
- Use regular
forloops instead of comprehensions (easier to add exception handling without cluttering the code).
Let's go with both approaches, starting with helper functions since they keep your code organized.
1. Handle dictNns Calculations
Your first dictionary has division op_dictNns[k]/v—if v is zero, this will fail. Let's make a helper function:
def calculate_nns_value(nns_val, v): try: ratio = 1 - (nns_val / v) adjusted_ratio = ratio * 0.15 # Return the NNS1 object as you originally did return NNS1(nns_val, v, float(ratio), float(adjusted_ratio)) except ZeroDivisionError: # Customize this handling to fit your needs print(f"Warning: Skipping entry where v = {v} (division by zero)") # You could return a default NNS1 object instead of None if needed return None
Now rewrite dictNns using this function:
op_dictNns = dict(result2.compute().values) data_nns_items = dict(dataNns.values).items() dictNns = { k: value for k, v in data_nns_items if (value := calculate_nns_value(op_dictNns[k], v)) is not None }
(We use the walrus operator := here to avoid calling the function twice—if you're on Python <3.8, use a loop instead.)
2. Handle dict2 Calculations
Similar fix for the op_dict[k]/v division here:
def calculate_summary_value(op_val, v): try: ratio = op_val / v adjusted_ratio = ratio * 0.70 return Summary(op_val, v, float(ratio), float(adjusted_ratio)) except ZeroDivisionError: print(f"Warning: Skipping entry where v = {v} (division by zero)") return None op_dict = dict(result.compute().values) data_items = dict(data.values).items() dict2 = { k: value for k, v in data_items if (value := calculate_summary_value(op_dict[k], v)) is not None }
3. Handle dict3 Calculations
This one has a twist: you're dividing op_dict3[k]/op_dict[k], so we need to handle cases where op_dict[k] is zero or missing (which would throw a KeyError). Let's add extra handling:
def calculate_mandate_value(op3_val, op_val, v): try: ratio = op3_val / op_val adjusted_ratio = ratio * 0.15 return Mandate(op3_val, v, float(ratio), float(adjusted_ratio)) except ZeroDivisionError: print(f"Warning: Skipping entry where op_val = {op_val} (division by zero)") return None except KeyError: print(f"Warning: Missing corresponding key in op_dict") return None op_dict3 = dict(result1.compute().values) dict3 = { k: value for k, v in data_items if (value := calculate_mandate_value(op_dict3[k], op_dict.get(k, 0), v)) is not None }
(We use op_dict.get(k, 0) to avoid KeyError if the key doesn't exist—adjust the default value if 0 isn't appropriate.)
If helper functions feel overwhelming, regular loops are more straightforward to debug:
# Example for dictNns dictNns = {} op_dictNns = dict(result2.compute().values) for k, v in dict(dataNns.values).items(): nns_val = op_dictNns[k] try: ratio = 1 - (nns_val / v) adjusted_ratio = ratio * 0.15 dictNns[k] = NNS1(nns_val, v, float(ratio), float(adjusted_ratio)) except ZeroDivisionError: print(f"Skipping key {k}: v is zero, can't compute value") # Optional: Assign a default value instead of skipping # dictNns[k] = NNS1(nns_val, v, 0.0, 0.0)
Instead of just printing warnings, you could:
- Log the error to a file using Python's
loggingmodule. - Assign a default value that makes sense for your use case (e.g.,
0.0for ratios). - Raise a custom exception if the error is critical.
内容的提问来源于stack exchange,提问作者Aditya Shingade

