W tym samouczku nauczysz się, jak obsługiwać wyjątki w programie w języku Python za pomocą instrukcji try, except i last, korzystając z przykładów.
Wideo: Obsługa wyjątków w Pythonie (spróbuj… z wyjątkiem… na końcu)
Wyjątki w Pythonie
Python ma wiele wbudowanych wyjątków, które są zgłaszane, gdy program napotka błąd (coś w programie idzie nie tak).
Gdy wystąpią te wyjątki, interpreter języka Python zatrzymuje bieżący proces i przekazuje go do procesu wywołującego, dopóki nie zostanie on obsłużony. Jeśli nie zostanie obsłużone, program ulegnie awarii.
Na przykład, rozważmy program, w którym mamy funkcję A
wywołującą funkcję B
, która z kolei wywołuje funkcję C
. Jeśli wyjątek występuje w funkcji, C
ale nie jest obsługiwany C
, wyjątek przechodzi do, B
a następnie do A
.
Jeśli nigdy nie został obsłużony, wyświetlany jest komunikat o błędzie i nasz program nagle nieoczekiwanie zatrzymuje się.
Łapanie wyjątków w Pythonie
W Pythonie wyjątki można obsługiwać za pomocą try
instrukcji.
Krytyczna operacja, która może zgłosić wyjątek, jest umieszczana wewnątrz try
klauzuli. Kod obsługujący wyjątki jest zapisany w except
klauzuli.
Możemy zatem wybrać, jakie operacje wykonać, gdy złapiemy wyjątek. Oto prosty przykład.
# import module sys to get the type of 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)
Wynik
Wpis to Ups! wystąpił. Następny wpis. Wpis to 0 Ups! wystąpił. Następny wpis. Wpis to 2 Odwrotność 2 to 0,5
W tym programie przeglądamy wartości z listy randomList. Jak wspomniano wcześniej, część, która może powodować wyjątek, jest umieszczana wewnątrz try
bloku.
Jeśli nie wystąpi żaden wyjątek, except
blok jest pomijany i normalny przepływ jest kontynuowany (dla ostatniej wartości). Ale jeśli wystąpi jakikolwiek wyjątek, zostanie przechwycony przez except
blok (pierwsza i druga wartość).
Tutaj drukujemy nazwę wyjątku za pomocą exc_info()
funkcji wewnątrz sys
modułu. Widzimy, że a
przyczyny ValueError
i 0
przyczyny ZeroDivisionError
.
Ponieważ każdy wyjątek w Pythonie dziedziczy po Exception
klasie bazowej , powyższe zadanie możemy również wykonać w następujący sposób:
# import module sys to get the type of exception import sys randomList = ('a', 0, 2) for entry in randomList: try: print("The entry is", entry) r = 1/int(entry) break except Exception as e: print("Oops!", e.__class__, "occurred.") print("Next entry.") print() print("The reciprocal of", entry, "is", r)
Ten program ma takie same wyniki, jak powyższy program.
Łapanie określonych wyjątków w Pythonie
W powyższym przykładzie nie wspomnieliśmy o żadnym konkretnym wyjątku w except
klauzuli.
Nie jest to dobra praktyka programistyczna, ponieważ wyłapuje wszystkie wyjątki i obsługuje każdy przypadek w ten sam sposób. Możemy określić, które wyjątki except
powinna przechwytywać klauzula.
try
Klauzula może mieć dowolną liczbę except
klauzul obsługiwać różne wyjątki, jednak tylko jeden zostanie zrealizowane w przypadku wystąpi wyjątek.
Możemy użyć krotki wartości, aby określić wiele wyjątków w klauzuli except. Oto przykładowy pseudokod.
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
Zgłaszanie wyjątków w Pythonie
W programowaniu w Pythonie wyjątki są zgłaszane, gdy wystąpią błędy w czasie wykonywania. Możemy również ręcznie zgłaszać wyjątki za pomocą raise
słowa kluczowego.
We can optionally pass values to the exception to clarify why that exception was raised.
>>> 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("That is not a positive number!")… except ValueError as ve:… print(ve)… Enter a positive integer: -2 That is not a positive number!
Python 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: Exceptions in the else clause are not handled by the preceding except clauses.
Let's look at an example:
# program to print the reciprocal of even numbers try: num = int(input("Enter a number: ")) assert num % 2 == 0 except: print("Not an even number!") else: reciprocal = 1/num print(reciprocal)
Output
If we pass an odd number:
Enter a number: 1 Not an even number!
If we pass an even number, the reciprocal is computed and displayed.
Enter a number: 4 0.25
However, if we pass 0, we get ZeroDivisionError
as the code block inside else
is not handled by preceding except
.
Enter a number: 0 Traceback (most recent call last): File "", line 7, in reciprocal = 1/num ZeroDivisionError: division by zero
Python try… 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.
For example, we may be connected to a remote data center through the network or working with a file or a Graphical User Interface (GUI).
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.
Here is an example of file operations to illustrate this.
try: f = open("test.txt",encoding = 'utf-8') # perform file operations finally: f.close()
Ten typ konstrukcji zapewnia zamknięcie pliku, nawet jeśli podczas wykonywania programu wystąpi wyjątek.