In programming, Handling exceptions is a must when it comes to real life applications. Python has many built-in exceptions that are raised when your program encounters an error. When these exceptions occur, the Python interpreter stops the current process and passes it to the calling process until it is handled. If not handled, the program will crash.
We must handle any exception raised within our application. We do that by use try and except.
Error being raised
result = 12 / 0
print(result)
# output
Traceback (most recent call last):
File "/Users/folaukaveinga/Github/python/main.py", line 101, in <module>
exceptions.show()
File "/Users/folaukaveinga/Github/python/exceptions.py", line 6, in show
result = 12 / 0
ZeroDivisionError: division by zero
Handling raised error
The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause.
try:
result = 12 / 0
print(result)
except ZeroDivisionError as e:
print(e)
print("done")
Here the program continued its executing to the end where is before it stopped when exception was raised.
Handling specific errors
A try clause can have any number of except clauses to handle different exceptions, however, only one will be executed in case an exception occurs.
try: # do something pass except ValueError: # handle ValueError exception pass except (TypeError, ZeroDivisionError): # handle multiple exceptions # TypeError and ZeroDivisionError pass except: # handle all other exceptions pass
Raise an error
Exceptions are raised by Python when errors occur at runtime. We can also manually raise exceptions using the raise keyword. We can optionally pass values to the exception to clarify why that exception was raised.
name = input("what is your name? ")
if name == None or len(name) ==0 :
raise ValueError("invalid name")
# output - if you don't put in anything
Traceback (most recent call last):
File "/Users/folaukaveinga/Github/python/main.py", line 101, in <module>
exceptions.show()
File "/Users/folaukaveinga/Github/python/exceptions.py", line 15, in show
raise ValueError("invalid name")
ValueError: invalid name
Try with else clause
In some situations, you might want to run a certain block of code if the code block inside try ran without any errors. For these cases, you can use the optional else keyword with the try statement. Note that exceptions in the else clause are not handled by the preceding except clauses.
try:
result = 12 / 0
print(result)
except ZeroDivisionError as e:
print(e)
else:
print("all good")
Try with finally
The try statement in Python can have an optional finally clause. This clause is executed no matter what, and is generally used to release external resources. In all these circumstances, we must clean up the resource before the program comes to a halt whether it successfully ran or not. These actions (closing a file, GUI or disconnecting from network) are performed in the finally clause to guarantee the execution.
try:
f = open("test.txt", encoding='utf-8')
# perform file operations
finally:
f.close()
print("file closed")