python_wiki:exceptions

This is an old revision of the document!


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)

  • python_wiki/exceptions.1505621663.txt.gz
  • Last modified: 2019/05/25 23:50
  • (external edit)