[ML&Py]×Alibaba Cloud Tianchi Python Training Camp (day3 check-in)-exception handling
1. Overview of learning content
1.1 Learning address: Aliyun Tianchi python training camp
1.2 Mind map
2. Specific learning content
2.1 Exception handling
Anomalies are errors detected during runtime. The computer language defines exception types for possible errors. When a certain error causes a corresponding exception, the exception handler will be started to restore the normal operation of the program.
2.1.1 Summary of Python standard exceptions
- BaseException: All abnormal base class
- Exception: Conventional abnormality base class
- StandardError: The base class for all built-in standard exceptions
- ArithmeticError: The base class for all numerical calculation exceptions
- FloatingPointError: floating point calculation exception
- OverflowError : Numerical operation exceeds the maximum limit
- ZeroDivisionError : division by zero
- AssertionError : the assertion statement (assert) failed
- AttributeError : Attempt to access unknown object attribute
- EOFError: No built-in input, EOF mark reached
- EnvironmentError: The base class of operating system exceptions
- IOError: Input/output operation failed
- OSError : An exception generated by the operating system (for example, opening a file that does not exist)
- WindowsError: system call failed
- ImportError : When importing a module fails
- KeyboardInterrupt: user interrupt execution
- LookupError: The base class for invalid data query
- IndexError : The index is out of the range of the sequence
- KeyError : Find a keyword that does not exist in the dictionary
- MemoryError : memory overflow (memory can be released by deleting the object)
- NameError : Attempt to access a variable that does not exist
- UnboundLocalError: Access to uninitialized local variables
- ReferenceError: Weak reference attempts to access objects that have been garbage collected
- RuntimeError: General runtime exception
- NotImplementedError: Method not yet implemented
- SyntaxError : exception caused by syntax error
- IndentationError: exception caused by indentation error
- TabError: Tab and space are mixed
- SystemError: General interpreter system exception
- TypeError : invalid operation between different types
- ValueError : Invalid parameter passed
- UnicodeError: Unicode related exception
- UnicodeDecodeError: exception during Unicode decoding
- UnicodeEncodeError: exception caused by Unicode encoding error
- UnicodeTranslateError: exception caused by Unicode conversion error
There are hierarchical relationships within the exception system. Some relationships in the Python exception system are as follows:
2.1.2 Summary of Python standard warnings
- Warning: the base class for warnings
- DeprecationWarning: warning about deprecated features
- FutureWarning: A warning that the semantics of the structure will change in the future
- UserWarning: warning generated by user code
- PendingDeprecationWarning: A warning that the feature will be deprecated
- RuntimeWarning: warning of suspicious runtime behavior (runtime behavior)
- SyntaxWarning: Suspicious syntax warning
- ImportWarning: Used to trigger a warning during the import of a module
- UnicodeWarning: warnings related to Unicode
- BytesWarning: warnings related to bytes or bytecode
- ResourceWarning: warnings related to resource usage
2.1.3 try-except statement
try:
检测范围
except Exception[as reason]:
出现异常后的处理代码
The try statement works as follows:
- First, execute the
try
clause ( the statement between the keywordtry
and the keywordexcept
) - If no exception occurs, the
except
clause is ignored , and thetry
clause ends after execution. - If
try
an exception occurs during the execution of the clause, thetry
rest of the clause will be ignored. If the type of the exceptionexcept
matches the name after it, the correspondingexcept
clause will be executed.try - except
The code after the last executed statement. - If an exception does not match any
except
, then the exception will be passed to the upper layertry
.
try:
f = open('test.txt')
print(f.read())
f.close()
except OSError:
print('打开文件出错')
# 打开文件出错
try:
f = open('test.txt')
print(f.read())
f.close()
except OSError as error:
print('打开文件出错\n原因是:' + str(error))
# 打开文件出错
# 原因是:[Errno 2] No such file or directory: 'test.txt'
A try
statement may contain multiple except
clauses to handle different specific exceptions. Only one branch will be executed at most.
try:
int("abc")
s = 1 + '1'
f = open('test.txt')
print(f.read())
f.close()
except OSError as error:
print('打开文件出错\n原因是:' + str(error))
except TypeError as error:
print('类型出错\n原因是:' + str(error))
except ValueError as error:
print('数值出错\n原因是:' + str(error))
# 数值出错
# 原因是:invalid literal for int() with base 10: 'abc'
dict1 = {
'a': 1, 'b': 2, 'v': 22}
try:
x = dict1['y']
except LookupError:
print('查询错误')
except KeyError:
print('键错误')
else:
print(x)
# 查询错误
try-except-else
The statement tried to query dict
a key-value pair that was not in, which caused an exception. This exception should belong to exactly KeyError
, but because it KeyError
is LookupError
a subclass and will be LookupError
placed KeyError
before it, the program executes the except
code block first. Therefore, when using multiple except
code blocks, you must adhere to the order of their specifications, from the most targeted exception to the most general exception.
dict1 = {
'a': 1, 'b': 2, 'v': 22}
try:
x = dict1['y']
except KeyError:
print('键错误')
except LookupError:
print('查询错误')
else:
print(x)
# 键错误
A except
clause can handle multiple exceptions that will be placed in a parenthesis as a tuple.
try:
s = 1 + '1'
int("abc")
f = open('test.txt')
print(f.read())
f.close()
except (OSError, TypeError, ValueError) as error:
print('出错了!\n原因是:' + str(error))
# 出错了!
# 原因是:unsupported operand type(s) for +: 'int' and 'str'
2.1.4 try-except-finally statement
try:
detection range
except Exception[as reason]:
processing code after an exception
finally: code that
will be executed anyway
Regardless of whether try
an exception occurs in the finally
clause , the clause will be executed.
If an exception try
is thrown in the clause without any except
interception, then the exception will be finally
thrown after the clause is executed.
def divide(x, y):
try:
result = x / y
print("result is", result)
except ZeroDivisionError:
print("division by zero!")
finally:
print("executing finally clause")
divide(2, 1)
# result is 2.0
# executing finally clause
divide(2, 0)
# division by zero!
# executing finally clause
divide("2", "1")
# executing finally clause
# TypeError: unsupported operand type(s) for /: 'str' and 'str'
2.1.5 try-except-else statement
If try
no exception occurs during the execution of the clause, Python will execute the else
statement following the statement.
try:
检测范围
except:
出现异常后的处理代码
else:
如果没有异常执行这块代码
except
It is not a good way to use it without any exception type. We cannot identify specific exception information through this program, because it catches all exceptions.
try:
detection range
except(Exception1[, Exception2[,...ExceptionN]]]):
if one of the above exceptions occurs, execute this code
else:
if there is no exception, execute this code
try:
fh = open("testfile.txt", "w")
fh.write("这是一个测试文件,用于测试异常!!")
except IOError:
print("Error: 没有找到文件或读取文件失败")
else:
print("内容写入文件成功")
fh.close()
# 内容写入文件成功
Note: else
The existence of a except
statement must be based on the existence of except
the try
statement. Using a statement in a else
statement without a statement will cause a grammatical error.
2.1.6 raise statement
Python uses the raise
statement to throw a specified exception.
try:
raise NameError('HiThere')
except NameError:
print('An exception flew by!')
# An exception flew by!
Three, study summary
I have only learned the try-except statement for the exception handling I encountered before, and I am not familiar with the various exception prompts encountered. I guess the meaning according to the English guess. After learning today, I have a deeper understanding of various exceptions and methods to handle exceptions. And more.
Today’s content is quite important. I’m not familiar with it before. The opening is completed on the third day. Come on (◍°∇°◍)ノ゙