Differences
This shows you the differences between two versions of the page.
python_wiki:exceptions [2017/09/17 00:15] billdozor [The Code] |
python_wiki:exceptions [2019/05/25 23:50] |
||
---|---|---|---|
Line 1: | Line 1: | ||
- | ====== Exceptions ====== | ||
- | |||
- | **General Information** | ||
- | |||
- | Attempting actions and catching exceptions/ | ||
- | |||
- | **Checklist** | ||
- | * Python 2 or 3 | ||
- | |||
- | ---- | ||
- | |||
- | ====== Usage ====== | ||
- | |||
- | Using the code snippet. | ||
- | <code bash> | ||
- | chmod +x try-except.py | ||
- | ./ | ||
- | |||
- | # Example output | ||
- | |||
- | my_number successfully converted to an integer. | ||
- | my_number2 is NOT an integer! | ||
- | </ | ||
- | |||
- | ---- | ||
- | |||
- | ====== The Code ====== | ||
- | |||
- | <code python try-except.py> | ||
- | # | ||
- | |||
- | # A number stored as a string | ||
- | my_number=" | ||
- | |||
- | try: | ||
- | # Attempt to convert to an integer | ||
- | my_number = int(my_number) | ||
- | print(" | ||
- | except: | ||
- | # If there is an error, display a message and exit | ||
- | print(" | ||
- | exit(1) | ||
- | |||
- | # Store a string | ||
- | my_number2=" | ||
- | |||
- | try: | ||
- | # Attempt to convert to an integer | ||
- | my_number2 = int(my_number2) | ||
- | print(" | ||
- | except: | ||
- | # If there is an error, display a message and exit | ||
- | print(" | ||
- | exit(1) | ||
- | </ | ||
- | |||
- | \\ | ||
- | Another example is using a try, except when using an API for logins. | ||
- | <code python> | ||
- | # Attempt to login and get a session id | ||
- | try: | ||
- | key = server.auth.login(spacewalk_login, | ||
- | except: | ||
- | print(" | ||
- | exit(1) | ||
- | </ | ||
- | * NOTE: The above code will not run by itself, as it is a snippet from using a Spacewalk API. | ||
- | |||
- | ---- | ||