Python Try...Except Comma VS 'As' in Except

Python try...except comma vs 'as' in except

The definitive document is PEP-3110: Catching Exceptions

Summary:

  • In Python 3.x, using as is required to assign an exception to a variable.
  • In Python 2.6+, use the as syntax, since it is far less ambiguous and forward compatible with Python 3.x.
  • In Python 2.5 and earlier, use the comma version, since as isn't supported.

Comma in except clause

It provides a variable name for the exception inside the except block:

>>> try:
... raise Exception('foo')
... except Exception, ex:
... print ex
... print type(ex)
...
foo
<type 'exceptions.Exception'>

I personally find the as syntax more clear:

>>> try:
... raise Exception('foo')
... except Exception as ex:
... print ex
... print type(ex)
...
foo
<type 'exceptions.Exception'>

But the as syntax wasn't introduced until 2.6, according to answers in this question.

Invalid Syntax in except handler when using comma

Change

except InvalidUserPass, e:

to

except InvalidUserPass as e:

See this for more info.

Try Except inside an elif, not working as desired

In this case, you probably want to use isinstance instead to test what kind of object you're working with.

if isinstance(obj, dict):
over_time = obj['overtime_approve']
elif isinstance(obj, UpdatedPunchRawDataProcesses): # Replace this with whatever your class actually is
over_time = obj.overtime_approve
else:
raise TypeError("obj should only be dict or apps.employee.models.UpdatedPunchRawDataProcesses")

if over_time == False:
friday_ot_hours = 0
holiday_ot_hours = 0
normal_hours = 0
normal_ot_hours = 0
total_hours = normal_ot_hours + normal_hours

In Python, what's the difference between 'except Exception as e' and 'except Exception, e'

This PEP introduces changes intended to help eliminate ambiguities in Python's grammar, simplify exception classes, simplify garbage collection for exceptions and reduce the size of the language in Python 3.0.

PEP 3110: "Catching Exceptions in Python 3000"

A better way than this nested try-except statement?

this is what you need. no try-except included.

import pycountry
code_1 =''
while True:
flag1 = input("Enter country 1: ")
aux = pycountry.countries.get(name=flag1) or pycountry.countries.get(official_name=flag1)
if aux ==None:
print("Invalid Input. Visit --- for list of country names.")
continue
code1 = aux.alpha_2
break
print(code1)

Remove all the characters and numbers except comma

Possible solution is the following:

# pip install pandas

import pandas as pd
pd.set_option('display.max_colwidth', 200)

# set test data and create dataframe
data = {"text": ['100 % polyester, Paperboard (min. 30% recycled), 100% polypropylene','Polypropylene plastic', '100 % polyester, Paperboard (min. 30% recycled), 100% polypropylene', 'Bamboo, Clear nitrocellulose lacquer', 'Willow, Stain, Solid wood, Polypropylene plastic, Stainless steel, Steel, Galvanized, Steel, 100% polypropylene', 'Banana fibres, Clear lacquer', 'Polypropylene plastic (min. 20% recycled)']}
df = pd.DataFrame(data)

def cleanup(txt):
re_pattern = re.compile(r"[^a-z, ()]", re.I)
return re.sub(re_pattern, "", txt).replace(" ", " ").strip()

df['text_cleaned'] = df['text'].apply(cleanup)
df

Returns

Sample Image

Try Except in python for FileNotFound doesn't stop the execution after the error

You can add some code that should run only if what's in the try statement doesn't raise an except state with else:

  • https://docs.python.org/3/tutorial/errors.html

Besides that, if you want your code to stop if an error is raised, use sys.exit() inside the except statement:

  • https://docs.python.org/3/library/sys.html

  • How do I stop a program when an exception is raised in Python?

However, as Aryerez stated, usually the point of the try-except statement is to prevent the code from crashing. If you want it to stop running if an error happens, you can just remove the try-catch statements altogether.



Related Topics



Leave a reply



Submit