Common Errors
NameError-- use undefined variables
SyntaxError-- grammatical errors, wrong format common program. As if a post is not:
IOError-- open a file or folder does not exist
ZeroDivisionError-- divide by zero error, that is, the denominator is zero
ValueError-- invalid incoming values, generated when the cast. As a = int ( 'dd')
KeyboardInterrupt-- keyboard interrupt error, resulting in the forced termination of the program.
error
Syntax error: Code does not meet the interpreter or compiler syntax
Logic Error: incomplete or invalid input or calculation problems
abnormal
Encountered a logical or arithmetic problems
During operation the computer error (not enough memory or IO error)
If no abnormalities are processed manually, then the exception is caught and handled by the interpreter, the method of treatment to ignore or terminate the program
the difference
Error is non-normal, it is simply not supposed to exist, such as indentation characters
An exception is a program operating conditions, rather than serious errors, such as user input is too large
Exception Handling
try/except
Abnormal capture can use try / except statement.
Example:
the while True : the try : the X- = int ( the INPUT ( " Please enter a number: " ) ) BREAK the except ValueError : Print ( " you entered is not a number, try entering again! " )
# Allow the user to enter a valid integer, but allows the user to interrupt the program (using Control-C or the method provided by the operating system). User information will lead to a disruption KeyboardInterrupt exception.
try/except...else
try / except statement has an optional else clause, if you use this clause, must be placed after all except clauses.
else clause will be executed when the try clause does not happen any exception.
Example:
for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
except IOError:
print('cannot open', arg)
else:
print(arg, 'has', len(f.readlines()), 'lines')
f.close()
# try 语句中判断文件是否可以打开,如果打开文件时正常的没有发生异常则执行 else 部分的语句,读取文件内容
try-finally 语句
try-finally 语句无论是否发生异常都将执行最后的代码。
实例:
try:
runoob()
except AssertionError as error:
print(error)
else:
try:
with open('file.log') as file:
read_data = file.read()
except FileNotFoundError as fnf_error:
print(fnf_error)
finally:
print('这句话,无论异常是否发生都会执行。')
#finally 语句无论异常是否发生都会执行:
抛出异常
Python 使用 raise 语句抛出一个指定的异常。
实例:
x = 10
if x > 5:
raise Exception('x 不能大于 5。x 的值为: {}'.format(x))
#如果 x 大于 5 就触发异常:
用户自定义异常
你可以通过创建一个新的异常类来拥有自己的异常。异常类继承自 Exception 类,可以直接继承,或者间接继承,
实例:
class MyError(Exception): def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
try:
raise MyError(2*2)
except MyError as e:
print('My exception occurred, value:', e.value)
raise MyError('oops!')
输出结果:
Traceback (most recent call last):
File "<stdin>", line 1, in ?
__main__.MyError: 'oops!'