Exception handling on the third day of Python clocking
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.
1. Python standard exception summary
- 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. Python standard warning summary
- 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
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
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
.
【example】
try:
f = open('test.txt')
print(f.read())
f.close()
except OSError:
print('打开文件出错')
# 打开文件出错
【example】
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.
【example】
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'
【example】
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.
【example】
dict1 = {
'a': 1, 'b': 2, 'v': 22}
try:
x = dict1['y']
except KeyError:
print('键错误')
except LookupError:
print('查询错误')
else:
print(x)
# 键错误
[Examples] 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'
4. try-except-finally statement
try:
检测范围
except Exception[as reason]:
出现异常后的处理代码
finally:
无论如何都会被执行的代码
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.
【example】
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'
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:
检测范围
except(Exception1[, Exception2[,...ExceptionN]]]):
发生以上多个异常中的一个,执行这块代码
else:
如果没有异常执行这块代码
【example】
try:
fh = open("testfile", "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.
6. The raise statement
Python uses the raise
statement to throw a specified exception.
【example】
try:
raise NameError('HiThere')
except NameError:
print('An exception flew by!')
# An exception flew by!
Practice questions :
1. Guess the number game
Title description:
The computer generates a random number between zero and 100, and then asks the user to guess. If the number guessed by the user is greater than this number, the prompt is too large, otherwise the prompt is too small. When the user happens to guess the computer, the computer will prompt, "Congratulations! The number is...". Before the user guesses each time, the program will output the user's first guess. If the user input is not a number at all, the program will tell the user "input is invalid".
(Try to use try catch exception handling structure to handle the input situation)
The random module is used to obtain random numbers.
# your code here
import random
ran_num = random.randint(0, 100)
print("请输入一个0到100之间的整数")
i=0
while True:
try:
i+=1
print("这是第"+str(i)+"次猜测")
guess=input("请猜测一个数字:")
guess_num=int(guess)
if guess_num > ran_num :
print("太大")
elif guess_num < ran_num :
print("太小")
else :
print("恭喜你猜到了这个数是"+str(guess_num))
break
except ValueError as error:
print("输入无效\n"+str(error))