Movatterモバイル変換


[0]ホーム

URL:


CodeQL documentation
CodeQL resources

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


[8]ページ先頭

©2009-2025 Movatter.jp