Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need a return statement after a Python exception?

I'm rather new to python, and I want to make sure I'm doing this correctly. I'd like to have an exception class:

class UnknownCommandReceived(Exception):
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return repr(self.value)

I will raise the exception at the end of this function if no regexes match:

def cmdType(self):
    match = re.match(r'(<[ \w]+>),\s*(\d+)?,?\s*(\d+)?', cmd, re.IGNORECASE)
    if match: 
        cmd_type = 'int_tool'
        return cmd_type, match

    match = re.match(r'LCD\(([^\)]*)\)?_?(RED|YELLOW|GREEN|TEAL|BLUE|VIOLET|OFF|ON|SELECT|LEFT|DOWN|RIGHT)?', cmd, re.IGNORECASE)
    if match: 
        cmd_type = 'lcd'
        return cmd_type, match

    match = re.match(r'buffer(_read|_num|_line)(\((\w)\))?', cmd, re.IGNORECASE)
    if match: 
        cmd_type = 'buffer'
        return cmd_type, match

    # ... More regex matches ... 

    raise UnknownCommandReceived( "cmdType received an unknown command" )

    # unecessary return?
    return 'None', None

My question is--if the exception is always raised, then do I not need a return statement at the end of the function? My apologies.. its a very basic question. My understanding is that an exception once an exception is raised, execution will never return to that point of the code (unless its a loop, or a function that is called again). It will go straight to the catch and continue from there?

like image 853
nckturner Avatar asked May 18 '13 08:05

nckturner


1 Answers

No you don't. The return statement is unreachable.

Also, static-analysis tools, such as pyflakes will report that as an error.

like image 53
shx2 Avatar answered Sep 18 '22 03:09

shx2