[[python_wiki:exceptions]]

Exceptions

General Information

Attempting actions and catching exceptions/errors.

Checklist

  • Python 2 or 3

Usage

Using the code snippet.

chmod +x try-except.py
./try-except.py
 
# Example output
 
my_number successfully converted to an integer.
my_number2 is NOT an integer!

The Code

try-except.py
#!/usr/bin/python
 
# A number stored as a string
my_number="123"
 
try:
  # Attempt to convert to an integer
  my_number = int(my_number)
  print("my_number successfully converted to an integer.")
except:
  # If there is an error, display a message and exit
  print("my_number is NOT an integer!")
  exit(1)
 
# Store a string
my_number2="nope"
 
try:
  # Attempt to convert to an integer
  my_number2 = int(my_number2)
  print("my_number2 successfully converted to an integer.")
except:
  # If there is an error, display a message and exit
  print("my_number2 is NOT an integer!")
  exit(1)


Another example is using a try, except when using an API for logins.

# Attempt to login and get a session id
try:
  key = server.auth.login(spacewalk_login, spacewalk_password)
except:
  print("->ERROR: Spacewalk Login failed. Exiting...")
  exit(1)
  • NOTE: The above code will not run by itself, as it is a snippet from using a Spacewalk API.

  • python_wiki/exceptions.txt
  • Last modified: 2019/05/26 03:50
  • (external edit)