Важно иметь способ обрабатывать ошибки.
Python предоставляет нам обработку исключений.
Если вы заключите строки кода вtry:
блокировать:
try:
# some lines of code
В случае возникновения ошибки Python предупредит вас, и вы сможете определить, какой тип ошибки произошел, с помощьюexcept
блоки:
try:
# some lines of code
except <ERROR1>:
# handler <ERROR1>
except <ERROR2>:
# handler <ERROR2>
Чтобы поймать все исключения, вы можете использоватьexcept
без какого-либо типа ошибки:
try:
# some lines of code
except <ERROR1>:
# handler <ERROR1>
except:
# catch all other exceptions
Вelse
блок запускается, если не было обнаружено исключений:
try:
# some lines of code
except <ERROR1>:
# handler <ERROR1>
except <ERROR2>:
# handler <ERROR2>
else:
# no exceptions were raised, the code ran successfully
Аfinally
блок позволяет выполнять какую-либо операцию в любом случае, независимо от того, произошла ошибка или нет
try:
# some lines of code
except <ERROR1>:
# handler <ERROR1>
except <ERROR2>:
# handler <ERROR2>
else:
# no exceptions were raised, the code ran successfully
finally:
# do something in any case
Конкретная ошибка, которая может произойти, зависит от выполняемой вами операции.
Например, если вы читаете файл, вы можете получитьEOFError
. Если вы разделите число на ноль, вы получитеZeroDivisionError
. Если у вас есть проблема с преобразованием типа, вы можете получитьTypeError
.
Попробуйте этот код:
result = 2 / 0
print(result)
Программа завершится с ошибкой
Traceback (most recent call last):
File "main.py", line 1, in <module>
result = 2 / 0
ZeroDivisionError: division by zeroand the lines of code after the error will not be executed.
Adding that operation in a try:
block lets us recover gracefully and move on with the program:
try:
result = 2 / 0
except ZeroDivisionError:
print('Cannot divide by zero!')
finally:
result = 1
print(result) # 1
You can raise exceptions in your own code, too, using the raise
statement:
raise Exception('An error occurred!')
This raises a general exception, and you can intercept it using:
try:
raise Exception('An error occurred!')
except Exception as error:
print(error)
You can also define your own exception class, extending from Exception:
class DogNotFoundException(Exception):
pass
pass
here means “nothing” and we must use it when we define a class without methods, or a function without code, too.
try:
raise DogNotFoundException()
except DogNotFoundException:
print('Dog not found!')
More python tutorials:
- Introduction to Python
- Installing Python 3 on macOS
- Running Python programs
- Python 2 vs Python 3
- The basics of working with Python
- Python Data Types
- Python Operators
- Python Strings
- Python Booleans
- Python Numbers
- Python, Accepting Input
- Python Control Statements
- Python Lists
- Python Tuples
- Python Sets
- Python Dictionaries
- Python Functions
- Python Objects
- Python Loops
- Python Modules
- Python Classes
- The Python Standard Library
- Debugging Python
- Python variables scope
- Python, accept arguments from command line
- Python Recursion
- Python Nested Functions
- Python Lambda Functions
- Python Closures
- Python Virtual Environments
- Use a GoPro as a remote webcam using Python
- Python, how to create a list from a string
- Python Decorators
- Python Docstrings
- Python Introspection
- Python Annotations
- Python, how to list files and folders in a directory
- Python, how to check if a number is odd or even
- Python, how to get the details of a file
- Python, how to check if a file or directory exists
- Python Exceptions
- Python, how to create a directory
- Python, how to create an empty file
- Python, the `with` statement
- Python, create a network request
- Python, installing 3rd party packages using `pip`
- Python, read the content of a file