English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this article, you will learn how to use try, except, and finally statements to handle exceptions in Python programs. This will inspire you to write clean, readable, and efficient code in Python.
Python has manyBuilt-in exceptions , when some errors occur, they will force your program to output errors.
When these exceptions occur, they will cause the current process to stop and pass it to the calling process until it is handled. If not handled, our program will crash.
For example, if function A calls function B, and function B calls function C, and an exception occurs in function C. If the exception is not handled in C, then the exception will be passed to B, and then to A.
If not handled, it will throw an error message, and our program will suddenly stop unexpectedly.
In Python, you can use the try statement to handle exceptions.
The critical operations that may cause an exception are placed in the try clause, and the code to handle the exception is written in the except clause.
After catching an exception, what operation we will perform depends on ourselves. This is a simple example.
# Import module sys to get the type of the exception import sys randomList = ['a', 0, 2] for entry in randomList: try: print("The entry is", entry) r = 1/int(entry) break except: print("Oops!", sys.exc_info()[0], "occurred.") print("Next entry.") print() print("The reciprocal of", entry, "is", r)
Output results
The entry is a Oops! <class 'ValueError'> occurred. Next entry. The entry is 0 Oops! <class 'ZeroDivisionError'> occurred. Next entry. The entry is 2 The reciprocal of 2 is 0.5
In this program, we loop until the user enters an integer with a valid reciprocal. The part that may cause an exception is placed in the try block.
If no exception occurs, the content outside the except block is skipped and the normal process continues. However, if any exception occurs, it will be caught by the except block.
Here, we use the exinfo() function from the sys module to print the name of the exception and ask the user to try again. We can see the value ‘a’ and ‘1.3‘0’ will cause ValueError, ‘0’ will cause ZeroDivisionError.
In the above example, we did not mention any exceptions in the except clause.
This is not a good programming habit because it will catch all exceptions and handle each case in the same way. We can specify which exceptions the except clause will catch.
A try clause can have any number of except clauses to handle them in different ways, but only one except clause is executed when an exception occurs.
We can use a tuple of values to specify multiple exceptions in the except clause. Here is a pseudocode example.
try: # Execute some code pass except ValueError: # Handling ValueError exception pass except (TypeError, ZeroDivisionError): # Handling multiple exceptions # TypeError and ZeroDivisionError exceptions pass except: # Handle all other exceptions pass
In Python programming, exceptions are thrown when corresponding errors occur at runtime, but we can use the keyword raise to force the throwing of exceptions.
We can also choose to pass values to exceptions to clarify why the exception was triggered.
>>> raise KeyboardInterrupt Traceback (most recent call last): ... KeyboardInterrupt >>> raise MemoryError("This is an argument") Traceback (most recent call last): ... MemoryError: This is an argument >>> try: ... a = int(input("Enter a positive integer:")) ... if a <= 0: ... raise ValueError("This is not a positive number!") ... except ValueError as ve: ... print(ve) ... Enter a positive integer: -2 This is not a positive number!
The try statement in Python can have an optional finally clause. This clause will be executed in any case, and it is usually used to release external resources.
For example, we can connect to a remote data center via network connection, or use files or use a graphical user interface (GUI).
In all these cases, whether the resource is successful or not, we must clear the resource. These operations (closing files, GUI, or disconnecting from the network) are executed in the finally clause to ensure execution.
This isFile OperationsThis example is used to illustrate this point.
try: f = open("test.txt", encoding = 'utf-8) # Execute file operations finally: f.close()
This type of construction ensures that the file is closed even if an exception occurs.