Explain Try / Except structure in practical examples?
Conditional clauses on `except` - Ideas - Discussions on Python.org
try catch - How to work with try and except in python? - Stack Overflow
Python: How to ignore an exception and proceed? - Stack Overflow
Videos
I am learning python and I've encountered the try / except part of it. I am struggling to understand when I would use this kind of code, probably because I am still very new and most of my code is small programs that have relied on conditional statments.
I guess in my brain I understand the logic of saying "try to do this but if it doesn't work just let it be and keep going with the code". My assumption is this is helpful on larger scale programs in wich you can't afford the time to make sure the code is fail proof and you need the code to buy you time to eventually go back once you have the fail proof option?
Was hoping someone could give me an example of a real life application or website and how this code could apply to it? Because I want to become comfortable with it but unsure how to.
TL,DR: Explain try/except in a practical example so I can understand when and where I would use it?
Thank you!
Okey, so there a few things that need to be explained where.
What is try-except used for?
It is used for catching errors raised by the program. Any code susceptible of raising an exception is inserted inside a try statement, and below that statement, any number of except statements with any single error that you want to catch.
try:
user_input = int(input('Give me a number: '))
except ValueError:
print('That is not a number!')
When should i use try-except?
It is not a good practice to use a try-except on every single line of code that could raise an error, because that may be half of it, or more. So when shall you use it? Simple, ask this question: Do I want to do any custom action with that error being raised? If the answer is yes, you are good to go.
Catching Exception or empty except
As I see in your example, you are using an empty except. Using an empty except statement will catch every single error raised that the surrounded code, which is similar (but not the same) as catching Exception. The Exception class is the superclass of every single built-in exception in the Python environment that are non-system-exiting (read here) and its generally a bad practice to catch either all exceptions with except: or Exception with except Exception:. Why? Because you are not letting the user (or even you, the programmer) know what error you are handling. For example:
fruits = ['apple', 'pear', 'banana']
try:
selection = fruits[int(input('Select a fruit number (0-2): '))]
except Exception:
print('Error!')
# But wait, are you catching ValueError because the user did not input a number,
# or are you catching IndexError because he selected an out of bound array index?
# You don't know
Catching multiple exceptions
Based on the previous example, you can use multiple try-except statements to difference which errors are being raised.
fruits = ['apple', 'pear', 'banana']
try:
selection = fruits[int(input('Select a fruit number (0-2): '))]
except ValueError:
print('That is not a number')
except IndexError:
print('That fruit number does not exist!')
Grouping exceptions
If there are two particular exceptions that you want to use for a same purpose, you can group them in a tuple:
fruits = ['apple', 'pear', 'banana']
try:
selection = fruits[int(input('Select a fruit number (0-2): '))]
except (ValueError, IndexError):
print('Invalid selection!')
Your case
Based on this information, add those try-except blocks to your code, and see what possible errors that could be raised during its execution, asking the previously recommended question Do I want to execute some custom action with this error?
Additionally
- There are
try-except-elsestatements. See here - There are
try-except-finallystatements. See here - You can combine them all in a
try-except1-except2...exceptN-else-finallystatement. - I recommend you get familiar with built-in errors why practicing this!
try: code that might cause an errorexcept: code that runs if an error happenselse: runs if no error happensfinally: always runs (good for cleanup, closing files, etc.)
Example 1: Basic Example
try:
num = int("abc") # This will raise an error
print("Number:", num)
except ValueError:
print("Oops! Could not convert to int.")
Example 2:
try:
x = 10 / 0
except ZeroDivisionError:
print("You cannot divide by zero!")
except ValueError:
print("Invalid value!")
Example 3:
try:
x = 5 / 1
except ZeroDivisionError:
print("Division by zero not allowed.")
else:
print("Division successful:", x) # runs if no error
finally:
print("Always runs, even if there was an error.")
Example 4: General
try:
# risky code
x = 10 / 0
y = int("abc")
except Exception as e:
print("Error occurred:", e)
except Exception:
pass
Python docs for the pass statement
Generic answer
The standard "nop" in Python is the pass statement:
try:
do_something()
except Exception:
pass
Using except Exception instead of a bare except avoid catching exceptions like SystemExit, KeyboardInterrupt etc.
Python 2
Because of the last thrown exception being remembered in Python 2, some of the objects involved in the exception-throwing statement are being kept live indefinitely (actually, until the next exception). In case this is important for you and (typically) you don't need to remember the last thrown exception, you might want to do the following instead of pass:
try:
do_something()
except Exception:
sys.exc_clear()
This clears the last thrown exception.
Python 3
In Python 3, the variable that holds the exception instance gets deleted on exiting the except block. Even if the variable held a value previously, after entering and exiting the except block it becomes undefined again.
Apart from a bare except: clause (which as others have said you shouldn't use), you can simply catch Exception:
import traceback
import logging
try:
whatever()
except Exception as e:
logging.error(traceback.format_exc())
# Logs the error appropriately.
You would normally only ever consider doing this at the outermost level of your code if for example you wanted to handle any otherwise uncaught exceptions before terminating.
The advantage of except Exception over the bare except is that there are a few exceptions that it wont catch, most obviously KeyboardInterrupt and SystemExit: if you caught and swallowed those then you could make it hard for anyone to exit your script.
You can but you probably shouldn't:
try:
do_something()
except:
print("Caught it!")
However, this will also catch exceptions like KeyboardInterrupt and you usually don't want that, do you? Unless you re-raise the exception right away - see the following example from the docs:
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except IOError as (errno, strerror):
print("I/O error({0}): {1}".format(errno, strerror))
except ValueError:
print("Could not convert data to an integer.")
except:
print("Unexpected error:", sys.exc_info()[0])
raise