PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, April 28, 2022

[FIXED] How to make static code analysis aware of an Exception throwing function?

 April 28, 2022     exception, function, python, warnings     No comments   

Issue

For reasons of readability and re-usability, I have a function that always raises a specific exception if called. However, this does not seem to be considered by static code analysis, i.e. I get unnecessary warnings. Is there any good way to avoid these warning, e.g., by making the static code analysis aware of the fact that this function will always raise an exception?

Minimal working example:

def raise_an_exception():
    raise Exception("...description...")


def foo(arg):
    if arg:
        x = 1
    else:
        raise_an_exception()
    # causes warning "Local variable 'x' might be referenced before assignment":
    return x + 1


def bar(arg):
    if arg:
        x = 1
    else:
        raise Exception("...description...")
    # causes no warning:
    return x + 1

Boundary condition: I do not want to declare x in foo() before the if statement or set x to any value in the else code block, or any other workaround like that. It is not necessary in bar() and it shouldn't be necessary in foo().


Solution

There's a NoReturn annotation for functions that can't return normally:

from typing import NoReturn

def raise_an_exception() -> NoReturn:
    raise Exception("...description...")

Static analysis tools that understand type annotations should understand this and not report an error for foo.



Answered By - user2357112
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing