Skip to content

Commit e8a482d

Browse files
committed
update
1 parent 3e1cb1d commit e8a482d

3 files changed

Lines changed: 44 additions & 8 deletions

File tree

docs/checks/exception_check.md

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
## Exception Statements
22

3-
Codeaudit detects the use of `pass` within an `except` block.
3+
Python Code Audit detects the use of `pass` within an `except` block.
44

55
The Python pattern:
66
```python
@@ -10,7 +10,7 @@ except Exception:
1010
pass
1111
```
1212

13-
presents potential security risks due to:
13+
Presents potential security risks due to:
1414
- **Overly broad exception handling** – catching `Exception` masks virtually all errors
1515
- **Silent failure** – using `pass` suppresses all evidence that something went wrong
1616

@@ -21,10 +21,16 @@ This security concern also applies when using `continue` inside an exception blo
2121
- `pass` statements in exception clauses
2222
- `continue` statements in exception clauses
2323

24+
:::{important}
25+
Treat the detection of `pass` and `continue` in exception handlers as a **signal** rather than proof of a security issue. Always examine whether the exception handler catches exceptions that are too broad (for example, `except:` or `except Exception:`).
26+
27+
No static analysis tool can determine with 100% confidence whether a particular exception handler represents a security risk. Due to Python's dynamic nature. The intent of the code, the surrounding context, and the runtime behavior all influence whether suppressing an exception is appropriate.
28+
:::
29+
2430

2531
## Background
2632

27-
Checking exception statements in Python code for possible security issues should be done.
33+
Checking exception statements in Python code for possible security issues should always be done.
2834
Reasons are e.g.:
2935

3036
1. **Masking of Critical Errors and Vulnerabilities:**
@@ -66,8 +72,11 @@ Reasons are e.g.:
6672
# Optionally, re-raise the exception if the program cannot continue meaningfully
6773
# raise
6874
```
75+
6976
* **Avoid `pass`:** Only use `pass` if the exception is truly expected and handling it means doing nothing, and you have documented why that's the case. Such scenarios are rare.
77+
7078
* **Use `finally` for Cleanup:** If resources need to be released regardless of whether an exception occurs, use a `finally` block or context managers (`with` statements).
79+
7180
```python
7281
try:
7382
f = open("my_file.txt", "r")
@@ -92,3 +101,4 @@ Reasons are e.g.:
92101
## More info
93102

94103
* [CWE-703: Improper Check or Handling of Exceptional Conditions](https://cwe.mitre.org/data/definitions/703.html)
104+
* [Python Security Handbook, Exception Statements](https://nocomplexity.github.io/pythonsecurity/constructs/exceptions/)

tests/test_correctexceptionuse.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
from codeaudit.filehelpfunctions import read_in_source_file
55
from codeaudit.issuevalidations import find_constructs
6+
from codeaudit.api_interfaces import filescan
67

78

89
def test_correct_exception_use():
@@ -17,7 +18,7 @@ def test_correct_exception_use():
1718
actual_data = find_constructs(source, constructs)
1819

1920
# This is the expected dictionary
20-
expected_data = {"pass": [19], "continue": [11]}
21+
expected_data = {"pass": [20, 38, 51], "continue": [12]}
2122

2223
# Assert that the actual data matches the expected data
2324
assert actual_data == expected_data

tests/validationfiles/exception.py

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
"""File to validate if pass is used in an except statement"""
22

3+
34
def divide(a, b):
45
"""
56
Divide a by b, handling ZeroDivisionError explicitly and
@@ -12,13 +13,13 @@ def divide(a, b):
1213
continue
1314

1415
try:
15-
result = a / b # May raise ZeroDivisionError
16+
result = a / b # May raise ZeroDivisionError
1617
except ZeroDivisionError:
1718
print("❌ Can't divide by zero!")
18-
result = None # handle and recover
19-
except Exception as exc: # catches *any* other error
19+
result = None # handle and recover
20+
except Exception as exc: # catches *any* other error
2021
# In real code, consider logging exc instead of pass
21-
pass # swallow the error (not recommended)
22+
pass # swallow the error (not recommended)
2223
result = None
2324
else:
2425
# Runs only if no exception was raised in the try block
@@ -28,3 +29,27 @@ def divide(a, b):
2829
print("🔚 Cleaning up—`finally` block executed.")
2930
return result
3031

32+
33+
def is_integer(text):
34+
"""pass is not a weakness"""
35+
try:
36+
int(text)
37+
return True
38+
except ValueError:
39+
# We intentionally don't do anything here.
40+
pass # nosec
41+
42+
print(f"'{text}' is not a valid integer.")
43+
return False
44+
45+
46+
def is_integer2(text):
47+
"""pass is a weakness"""
48+
try:
49+
int(text)
50+
return True
51+
except ValueError:
52+
# We intentionally don't do anything here.
53+
pass
54+
55+
return False

0 commit comments

Comments
 (0)