Except block handles ‘BaseException’¶
ID: py/catch-base-exceptionKind: problemSecurity severity: Severity: recommendationPrecision: very-highTags: - quality - reliability - error-handling - external/cwe/cwe-396Query suites: - python-security-and-quality.qls
Click to see the query in the CodeQL repository
All exception classes in Python derive fromBaseException.BaseException has three important subclasses,Exception from which all errors and normal exceptions derive,KeyboardInterrupt which is raised when the user interrupts the program from the keyboard andSystemExit which is raised by thesys.exit() function to terminate the program.
SinceKeyboardInterrupt andSystemExit are special they should not be grouped together with otherException classes.
CatchingBaseException, rather than its subclasses may prevent proper handling ofKeyboardInterrupt orSystemExit. It is easy to catchBaseException accidentally as it is caught implicitly by an emptyexcept: statement.
Recommendation¶
HandleException,KeyboardInterrupt andSystemExit separately. Do not use the plainexcept: form.
Example¶
In these examples, a functionapplication.main() is called that might raiseSystemExit. In the first two functions,BaseException is caught, but this will discardKeyboardInterrupt. In the third function,call_main_program_fixed onlySystemExit is caught, leavingKeyboardInterrupt to propagate.
In these examplesKeyboardInterrupt is accidentally ignored.
defcall_main_program_implicit_handle_base_exception():try:#application.main calls sys.exit() when done.application.main()exceptExceptionasex:log(ex)except:passdefcall_main_program_explicit_handle_base_exception():try:#application.main calls sys.exit() when done.application.main()exceptExceptionasex:log(ex)exceptBaseException:passdefcall_main_program_fixed():try:#application.main calls sys.exit() when done.application.main()exceptExceptionasex:log(ex)exceptSystemExit:pass
References¶
Python Language Reference:The try statement,Exceptions.
M. Lutz, Learning Python, Section 35.3: Exception Design Tips and Gotchas, O’Reilly Media, 2013.
Python Tutorial:Errors and Exceptions.
Common Weakness Enumeration:CWE-396.