GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • CodeQL documentation
  • CodeQL overview
  • Writing CodeQL queries
  • CodeQL language guides
  • QL language reference
  • CodeQL standard-libraries
  • CodeQL query help
  • CodeQL repository
  • QL publications
  • CodeQL query help for C and C++
  • CodeQL query help for C#
  • CodeQL query help for GitHub Actions
  • CodeQL query help for Go
  • CodeQL query help for Java and Kotlin

This view

  • Original page
  • New address

GeezerVison is showing codeql.github.com — Unreachable except block — CodeQL query help documentation

Unreachable except block¶

ID: py/unreachable-except
Kind: problem
Security severity: 
Severity: error
Precision: very-high
Tags:
   - quality
   - reliability
   - error-handling
   - external/cwe/cwe-561
Query suites:
   - python-code-quality.qls
   - python-security-and-quality.qls

Click to see the query in the CodeQL repository

When handling an exception, Python searches the except blocks in source code order until it finds a matching except block for the exception. An except block, except E:, specifies a class E and will match any exception that is an instance of E.

If a more general except block precedes a more specific except block, then the more general block is always executed and the more specific block is never executed. An except block, except A:, is more general than another except block, except B:, if A is a super class of B.

For example: except Exception: is more general than except Error: as Exception is a super class of Error.

Recommendation¶

Reorganize the except blocks so that the more specific except is defined first. Alternatively, if the more specific except block is no longer required, then it should be deleted.

Example¶

In the following example, the except Exception: will handle AttributeError preventing the subsequent handler from ever executing.



def incorrect_except_order(val):
    try:
        val.attr
    except Exception:
        print ("Exception")
    except AttributeError:
        print ("AttributeError")
        

References¶

  • Python Language Reference: The try statement, Exceptions.

  • Common Weakness Enumeration: CWE-561.

  • © GitHub, Inc.
  • Terms
  • Privacy
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.