When we are making a program, it’s possible to be interrupted bu some mistakes. These mistakes are sometimes called errors in Python. These errors in python can be Syntax errors and Exceptions. A error in the program will cause the program stop execution. On the other hand, exceptions are raised when some internal events occur which changes the normal flow of the program.
Try-except
When Exception errors occur, Try and Except statements are used to handle these errors in python codes. The codes in the try block will be tested when executed. If there is no errors, only the codes in the try block will be executed as normal. When some errors exist, the codes in the except block will be executed. The syntax is:
try:
# some codes may or may not have error
except:
# executed if some errors in the try block
Example 1: use try except but no error exists. Only the try block will be executed.
# try-except without error
def division(x, y):
try:
res = x / y
print(f"the result of {x}/{y} is {res}")
except:
print("there are some errors, please check your codes")
division(120, 20)Output:
the result of 120/20 is 6.0
Example 2: use try except when some errors exist. Only the except block will be executed.
# try-except with some errors
def division(x, y):
try:
res = x / y
print(f"the result of {x}/{y} is {res}")
except:
print("there are some errors, please check your codes")
division(120, 0)Output:
there are some errors, please check your codes
We can also specify what Exception error we are catching in the except statement.
# specify error type
def division(x, y):
try:
res = x / y
print(f"the result of {x}/{y} is {res}")
except ZeroDivisionError:
print("you are dividing by 0")
division(120, 0)Output:
you are dividing by 0
We can define as many except blocks as we want. The eariest except block that catches the error will be executed. Note: if there is a default except block, it needs to be in the last one.
def division(x, y):
try:
res = x / y
print(f"the result of {x}/{y} is {res}")
except NameError:
print("there is a name error")
except ZeroDivisionError:
print("you are dividing by 0")
except:
print("some errors exists")
division(120, 0)Output:
you are dividing by 0
Sometimes we don’t know exactly what errors may occur, and we would like to know the error type, there is another way of except statement that can show us the error details.
def division(x, y):
try:
res = x / y
print(f"the result of {x}/{y} is {res}")
except Exception as e:
print(f"the error is: {e}")
division(120, 0)
division(3, "a")Output:
the error is: division by zero the error is: unsupported operand type(s) for /: 'int' and 'str'
Try-except-else
In Python, we can add a else statement after all except statements. The codes in the else block will be executed only there is no exception raised in the try block.
The syntax is:
try:
# some codes may or may not have error
except:
# executed if some errors in the try block
else:
# executed if no exception is raised in try block
For example:
# try-except-else without error
def division(x, y):
try:
res = x / y
except Exception as e:
print(f"the error is: {e}")
else:
print(f"the result of {x}/{y} is {res}")
division(120, 60)
division(3, "a")Output:
the result of 120/60 is 2.0 the error is: unsupported operand type(s) for /: 'int' and 'str'
Try-except-finally
Python provides a keyword finally, which is always executed after the try and except blocks. The finally block has to be after all try-except blocks, and the codes in the finally block will be executed no matter whether there is error or not.
The syntax is:
try:
# some codes may or may not have error
except:
# executed if some errors in the try block
finally:
# some codes (always executed)
Small note: the finally block can be used together with else block, but the finally block has to be in the last one.
def division(x, y):
try:
res = x / y
except Exception as e:
print(f"the error is: {e}")
else:
print(f"the result of {x}/{y} is {res}")
finally:
print("this function is finished")
print("function call 1:")
division(120, 60)
print("function call 2:")
division(3, 0)Output:
function call 1: the result of 120/60 is 2.0 this function is finished function call 2: the error is: division by zero this function is finished
Raising a error
When we are getting inout from user or passing some arguments to a function, it’s always a good idea to check whether the input is valid to avoid some potential mistake. In this case, instead of using try-except block, we can check the inputs manually and raise an error if the input is invalid.
def get_input():
in_str = input("please enter a number: ")
if not in_str.isdigit():
raise ValueError
else:
print(f"The number you enter is {in_str}")
get_input()Output:
please enter a number: asc
Traceback (most recent call last):
File "D:\PythonProjects\main.py", line 83, in <module>
get_input()
File "D:\PythonProjects\main.py", line 76, in get_input
raise ValueError
ValueError
More specifically, we can define our own error message in the raise statement to indicate the users.
def get_input():
in_str = input("please enter a number: ")
if not in_str.isdigit():
raise ValueError("You should type a number")
else:
print(f"The number you enter is {in_str}")
get_input()Output:
please enter a number: abc
Traceback (most recent call last):
File "D:\PythonProjects\main.py", line 83, in <module>
get_input()
File "D:\PythonProjects\main.py", line 76, in get_input
raise ValueError("You should type a number")
ValueError: You should type a number
