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-else
statements. See here
- There are
try-except-finally
statements. See here
- You can combine them all in a
try-except1-except2...exceptN-else-finally
statement.
- I recommend you get familiar with built-in errors why practicing this!