python_wiki:exceptions

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

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/errors.  
- 
-**Checklist** 
-  * Python 2 or 3 
- 
----- 
- 
-====== Usage ====== 
- 
-Using the code snippet. 
-<code bash> 
-chmod +x try-except.py 
-./try-except.py 
- 
-# Example output 
- 
-my_number successfully converted to an integer. 
-my_number2 is NOT an integer! 
-</code> 
- 
----- 
- 
-====== The Code ====== 
- 
-<code python 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) 
-</code> 
- 
-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, spacewalk_password) 
-except: 
-  print("->ERROR: Spacewalk Login failed. Exiting...") 
-  exit(1) 
-</code> 
-  * 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/25 23:50
  • (external edit)