Bootstrap FreeKB - Python (Scripting) - error handling with try except else finally
Python (Scripting) - error handling with try except else finally

Updated:   |  Python (Scripting) articles

In a Python script, try except else finally can be used to do something based on whether or not some condition returns an exception. For example, let's say the "foo" variable has not been defined.

#!/usr/bin/python3
try:
  foo
except NameError:
  print(NameError)
  sys.exit(1)
else:
  print(f"the foo variable exists and contains a value of: {foo}")
finally:
  print(f"code in the finally block is always executed!")

 

Running this script should return something like this if the foo variable does not exist. In this scenario, the code in the else block was not used since the code in the except block was used.

<type 'exceptions.NameError'>
code in the finally block is always executed!

 

In this example, the foo variable exists.

#!/usr/bin/python3
foo = "Hello World"

try:
  foo
except NameError:
  print(NameError)
  sys.exit(1)
else:
  print(f"the foo variable exists and contains a value of: {foo}")
finally:
  print(f"code in the finally block is always executed!")

 

Which should now return the following.

the foo variable exists and contains a value of: Hello World
code in the finally block is always executed!

 

Or like this, using a boolean.

#!/usr/bin/python3
foo = True

try:
  foo
except NameError:
  print(NameError)
  sys.exit(1)
else:
  print(f"the foo boolean exists and contains a value of: {foo}")
finally:
  print(f"code in the finally block is always executed!")

 

Which should now return the following.

the foo variable exists and contains a value of: True
code in the finally block is always executed!

 

And here is how you could check for two (or more).

#!/usr/bin/python
foo = True

try:
  foo or bar
except NameError:
  print(NameError)
  sys.exit(1)
else:
  print("foo or bar have been defined")
finally:
  print(f"code in the finally block is always executed!")

 

KeyError can be used to determine if a key exists in a dictionary.

#!/usr/bin/python
dictionary = {
  "foo": "Hello",
  "bar": "World"
}

try:
  dictionary['bogus']
except KeyError:
  print("dictionary does not contain key 'bogus'")
  pass
else:
  print(dictionary['bogus'])

 

Or in a JSON object.

#!/usr/bin/python
import json

raw_json = '{ "foo": "nope" }'
json = json.loads ( raw_json )

try:
  json[bar]
except KeyError:
  print(KeyError)
  print("JSON does not contain bar key")
  sys.exit(1)
else:
  print("JSON contains bar key")

 


pass can be used if you simply want to move along, ignoring the exception.

#!/usr/bin/python
try:
  foo
except NameError:
  pass
else:
  print "the foo variable exists"

 

continue can be used to move onto the next item in a loop.

for item in list:
  try:
    item
  except NameError:
    print f"the {item} variable does NOT exists"
    continue
  else:
    print f"the {item} variable exists"

 


try multiple

Here is how you can check for two (or more) conditions. This will perform an and condition, not an or condition. In this example, both foo and bar must be defined to make it to the else statement.

#!/usr/bin/python
try:
  foo and bar
except NameError:
  print("foo or bar are defined")
else:
  print("both foo and bar are defined")

 

Or like this, with foo and bar on their own lines.

#!/usr/bin/python
try:
  foo
  bar
except NameError:
  print("foo or bar are defined")
else:
  print("both foo and bar are defined")

 


Nested

Here is an example of how you could use nested try except else.

#!/usr/bin/python3
foo = "Hello"
bar = "World"

try:
  foo
except NameError:
  print NameError
else:
  print(f"the foo variable exists and contains a value of: {foo}")
  try:
    bar
  except NameError:
    print NameError
  else:
    print(f"the bar variable exists and contains a value of: {bar}")

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 77a908 in the box below so that we can be sure you are a human.