T09 · Insecure Skill Coding Practices
- Location
main.py:62- Finding
Unrecognized Expense Records Cause an Unhandled KeyError
- Content
View full analysis
Tuple[str, float]: """Classify an expense.""" amount = self.extract_amount(text) if amount == 0: return ('', 0) for keyword, expense_type in self.expense_keywords['type_map'].items(): if keyword in text: return (expense_type, amount) return ('其他支出', amount) ``` ```python expense = { '原材料成本': 0.0, '房租成本': 0.0, '人工成本': 0.0, '水电杂费': 0.0, '其他成本': 0.0, '总支出': 0.0 } for line in lines: # Determine whether the record is income or expense. is_income = any(keyword in line for keyword in self.income_keywords['income']) is_expense = any(keyword in line for keyword in self.expense_keywords['expense']) if is_income: inc_type, amount = self.classify_income(line) if inc_type: income[inc_type] += amount income['总收入'] += amount elif is_expense: exp_type, amount = self.classify_expense(line) if exp_type: expense[exp_type] += amount expense['总支出'] += amount ``` ```python elif '付' in line or '花' in line or '出' in line: expense['其他支出'] += amount expense['总支出'] += amount ``` ### Technical Analysis The initialized `expense` dictionary defines the catch-all category `其他成本`, but both uncategorized-expense paths use the different key `其他支出`. When an expense record contains a general expense indicator but does not contain a subtype represented by `expense_keywords['type_map']`, `classify_expense()` returns `('其他支出', amount)`. The subsequent statement `expense[exp_type] += amount` accesses a key that does not exist and raises an unhandled `KeyError`. The heuristic fallback branch contains the same invalid dictionary a ...[truncated 1284 chars]- Remediation
View remediation
