File tree Expand file tree Collapse file tree 2 files changed +22
-4
lines changed
main/java/org/sonar/python/checks
test/resources/checks/incorrectExceptionType Expand file tree Collapse file tree 2 files changed +22
-4
lines changed Original file line number Diff line number Diff line change @@ -46,16 +46,19 @@ public void initialize(Context context) {
46
46
return ;
47
47
}
48
48
Expression raisedExpression = raiseStatement .expressions ().get (0 );
49
- if (!raisedExpression .type ().canBeOrExtend (BASE_EXCEPTION )) {
50
- ctx .addIssue (raiseStatement , MESSAGE );
51
- return ;
52
- }
53
49
Symbol symbol = null ;
54
50
if (raisedExpression instanceof HasSymbol ) {
55
51
symbol = ((HasSymbol ) raisedExpression ).symbol ();
56
52
} else if (raisedExpression .is (Tree .Kind .CALL_EXPR )) {
57
53
symbol = ((CallExpression ) raisedExpression ).calleeSymbol ();
58
54
}
55
+ if (hasGlobalOrNonLocalUsage (symbol )) {
56
+ return ;
57
+ }
58
+ if (!raisedExpression .type ().canBeOrExtend (BASE_EXCEPTION )) {
59
+ ctx .addIssue (raiseStatement , MESSAGE );
60
+ return ;
61
+ }
59
62
if (!mayInheritFromBaseException (symbol )) {
60
63
ctx .addIssue (raiseStatement , MESSAGE );
61
64
}
@@ -77,4 +80,8 @@ private static boolean mayInheritFromBaseException(@Nullable Symbol symbol) {
77
80
// to handle other builtins like 'NotImplemented'
78
81
return !BuiltinSymbols .all ().contains (symbol .fullyQualifiedName ());
79
82
}
83
+
84
+ private static boolean hasGlobalOrNonLocalUsage (@ Nullable Symbol symbol ) {
85
+ return symbol != null && symbol .usages ().stream ().anyMatch (s -> s .tree ().parent ().is (Tree .Kind .GLOBAL_STMT , Tree .Kind .NONLOCAL_STMT ));
86
+ }
80
87
}
Original file line number Diff line number Diff line change @@ -142,3 +142,14 @@ def raise_with_str_concat():
142
142
143
143
def raise_builtin_exception_with_fqn_null ():
144
144
raise IOError ()
145
+
146
+
147
+ def no_fp_on_nonlocal_variables (x ):
148
+ exception = None
149
+ def do_something ():
150
+ nonlocal exception
151
+ if foo ():
152
+ exception = ValueError ("Hello" )
153
+ do_something ()
154
+ if exception :
155
+ raise exception
You can’t perform that action at this time.
0 commit comments