Catching Exceptions in Python
Python has a lot of situations that cause exceptions compared to other programming languages.
Let's take a closer look at them. Let's say we have a list:
lst = [1, 2, 3]
Let's look at a non-existent list element:
print(lts[4])
After executing the code, an error (exception) will be displayed:
IndexError: list index out of range
If we want to continue working without throwing an exception, we should catch it using the try-except
construct. It has the following syntax:
try:
# code that throws the except exception:
# error handling
The try
block should contain code that may contain an exception. If an exception occurs during the execution of this code, the code execution will not stop, but will go to the code of the except
block. In this block, you should write the output of a message that describes the essence of the error that occurred as accurately as possible.
If no exceptional situations occurred during the execution of the try
block, then the useful code will simply be executed, but the code from the except
block will not.
Let's catch our exception when accessing a non-existent list element. To do this, we'll place the code with a potential error in the try
block. And in the except
block, we'll specify the console output of the message 'error:
elem is not exist'
:
lst = [1, 2, 3]
try:
print(lst[4])
except:
print('error: elem is not exist')
After executing the code, the following will be displayed:
'error: elem is not exist'
After learning the try-except
construct, the style of your code should change. Now all places where an exceptional situation may occur should be wrapped in try
, and the reaction to this exception should be written in the except
block.
Ask the user for two numbers. Divide one by the other. Catch the division by zero exception.
Ask the user for a number. Find the square root of that number. Catch the exception of taking the root of a negative number.
Given a list. Ask the user for an integer. Get the list element whose number the user entered. Catch the exception that occurs if the user entered a number outside the range of the list.
The following code is given:
num = '5'
res = num + 2
print(res)
What's wrong with this code? Fix its flaws.
The following code is given:
lst = [1, 2, 3, 4]
def getElem(iter):
print(iter[4])
getElem(lst)
What's wrong with this code? Fix its flaws.