The use of try in python
In Python, try
is the keyword used for exception handling. try
The syntax of the statement is as follows:
try:
# 可能会抛出异常的语句块
except ExceptionType1:
# 处理 ExceptionType1 异常的语句块
except ExceptionType2:
# 处理 ExceptionType2 异常的语句块
else:
# 如果没有异常发生,执行的语句块
finally:
# 不管有没有异常,都会执行的语句块
Among them, try
the code in the statement block may throw an exception. If an exception is thrown, it will be try
interrupted in the statement block and jump to the corresponding except
statement block to handle the exception. The exception type to be handled can be specified in the statement block. If the exception thrown is of the specified type, the code in the except
corresponding statement block will be executed .except
If try
no exception is thrown in the statement block, else
the code in the statement block will be executed. finally
The code in the statement block will be executed regardless of whether there is an exception.
The following is a simple example demonstrating try
the use of statement blocks:
try:
x = int(input("请输入一个整数: "))
print("输入的整数是:", x)
except ValueError:
print("输入错误:请输入整数")
else:
print("没有发生异常")
finally:
print("程序执行完毕")
In this example, try
the code in the block attempts to convert user input into an integer and outputs the converted result. If the user input is not an integer, ValueError
an exception will be thrown, and then jump to the corresponding except
statement block to handle the exception. In except
the statement block, we output an error message telling the user that the input was incorrect. In else
the statement block, we output a message indicating that no exception occurred. In finally
the statement block, we output a message indicating that the program has completed execution, regardless of whether an exception occurs or not.
Custom exception
ValueError
It is one of Python's built-in exception types. It usually indicates that the parameters received by a function or method are invalid or illegal. For example, when trying to convert a string to an integer, an exception will be thrown if the string is not a legal number ValueError
.
In Python, in addition to the built-in exception types, you can also customize exception types. In order to customize an exception type, you can define a new class and inherit from the Exception
class or other built-in exception types. For example, the following code defines a custom exception type MyError
:
class MyError(Exception):
pass
After defining MyError
the exception type, you can throw this exception in the program. For example:
def my_function(x):
if x < 0:
raise MyError("x不能小于0")
else:
return x * 2
try:
result = my_function(-1)
except MyError as e:
print("发生了自定义异常:", e)
else:
print("结果是:", result)
In this example, we define a my_function()
function called that takes a number x
and multiplies it by 2. If x
is a negative number, an exception is thrown MyError
and an error message is printed. In try
the statement block, we called my_function(-1)
, and since -1
is a negative number, MyError
an exception will be thrown. In except
the statement block, we catch this exception and print the error message. In else
the statement block, we output the calculation results.
Built-in exceptions
There are many built-in exception types in Python, which can be used to handle different types of errors. The following are common exception types and their descriptions built into Python 3.9.6 version:
Exception
: Base class for all exceptions.AttributeError
: The object does not have this attribute.EOFError
: No built-in input, EOF mark reached.FileExistsError
: When creating a file or directory, it was found that the file or directory already exists.FileNotFoundError
: The file or directory does not exist.ImportError
: Module import failed.IndexError
: This index does not exist in the sequence.KeyError
: This key does not exist in the map.KeyboardInterrupt
: User interrupts execution.MemoryError
: Memory overflow error.NameError
: Undeclared/initialized object (no properties).NotImplementedError
: The abstract method is not implemented.OSError
: Operating system errors, such as file open/read errors.OverflowError
: Numerical operation exceeds the maximum value.RecursionError
: The recursion is nested too deeply.RuntimeError
: Generic runtime error.StopIteration
:The iterator has no more values.SyntaxError
:Grammatical errors.IndentationError
: Indentation error.TabError
: Mix tab and space.SystemError
:Interpreter internal error.TypeError
: The operation or function is applied to an inappropriate type.UnboundLocalError
: Access uninitialized local variables.UnicodeError
:Unicode related errors.ValueError
: An operation or function received an argument with an incorrect value.ZeroDivisionError
: The divisor is zero.
It should be noted that these are only some of the exception types built into Python. There are many other exception types, and you can also customize exception types. When writing code, you can choose the appropriate exception type to handle errors as needed.