In this post, we will see how to manage Try/Except in Python.
Just to remember what try/except is:
Try/Except is a statement marks a block of statements to try and specifies a response should an exception be thrown.
In detail, in Try/Except we have three blocks:
Try, used to test a block of code for errors.
Except, used to handle the error.
Finally, used to execute code (regardless of the result of the try and except blocks).
Python has many Built-in Exceptions that we can use in our programs and here, we can find the complete list.
Now, we will see some examples:
ZERODIVISIONERROR
print("Test a division from v1/v2")
val1 = input("Insert v1 value: ")
val2 = input("Insert v2 value: ")
try:
val3 = int(val1)/int(val2)
print(f"The result is {val3}")
except ZeroDivisionError as error:
print(error)
finally:
print("Finally executed")
If we run the code, this will be the result:
FILENOTFOUNDERROR
We create a file txt called testpython.txt and we save it in the same folder of our Python code.
# definition of a function to read a text file and print lines by lines
def ReadAndShowLineByLine():
try:
# we try to open the file
readFile = open("testpython.txt", "r")
except FileNotFoundError as error:
print(error)
else:
# If there aren't errors, we run this code
lines = readFile.readlines()
for item in lines:
# print the single rows
print(item.strip())
# close the file
readFile.close()
finally:
print("Finally")
If we run the code, this will be the result:
Now, if we change in the code the name of the file, for example in “testpythone2.txt” and we run the code, this will be the result:
CATCH MULTIPLE EXCEPTIONS
Obviously, we can use multiple exceptions in order to catch more different errors.
Using our first code, we could add a catch in order to handle wrong values in input:
print("Test a division from v1/v2")
val1 = input("Insert v1 value: ")
val2 = input("Insert v2 value: ")
try:
val3 = int(val1)/int(val2)
print(f"The result is {val3}")
except ZeroDivisionError as error:
print(error)
except ValueError as error:
print("You must enter numeric value")
print(error)
finally:
print("Finally executed")
If we run the application, this will be the result:
GENERIC CATCH
If we neither don’t know or don’t want to catch a particular error, we can use a generic exception:
print("Test a division from v1/v2")
val1 = input("Insert v1 value: ")
val2 = input("Insert v2 value: ")
try:
val3 = int(val1)/int(val2)
print(f"The result is {val3}")
except Exception as error:
print("Something went wrong")
print(error)
finally:
print("Finally executed")
If we run the code, this will be the result:
Finally, we can use the generic exception as the last one in our code:
print("Test a division from v1/v2")
val1 = input("Insert v1 value: ")
val2 = input("Insert v2 value: ")
try:
val3 = int(val1)/int(val2)
print(f"The result is {val3}")
except ZeroDivisionError as error:
print(error)
except Exception as error:
print("Something went wrong")
print(error)
finally:
print("Finally executed")
If we run the code, this will be the result: