python (ten) - exception handling

1. What is an exception?

1.1 Definition

  • Errors are errors in the system that cannot be changed and handled by the programmer, such as system crashes, insufficient memory space, and method call stack overflow. Encountered such an error, it is recommended to terminate the program.
  • Exception means an exception that the program can handle, which can be caught and possibly recovered. When encountering such an exception, the exception should be handled as much as possible to make the program run again, and the exception should not be terminated at will.

1.2 Reasons for the exception

AttributeError 、IOError 、ImportError 、IndexError、
SyntaxError、TypeError、ValueError、KeyError、NameError
常见错误:
	IndentationError: 缩进错误
	KeyboardInterrupt:  Ctrl+C被按下
	UnboundLocalError : 有同名的全局变量
#异常原因示例
#print(a)    #NameError
#print(10/0)   #ZeroDivisionError
# d = {'name':10}
# print(d['age'])   #KeyError: 'age'
# with open('hello.py') as f:   #FileNotFoundError
#     pass

# a=b=18
# if a>b:
#     print('错误')
#  else:
#     print('正确')  #IndentationError

2. Exception handling mechanism

Official address
Insert picture description here

-  Python 的异常机制主要依赖 try 、except 、else、finally 和 raise 五个关键字。
		try 关键字后缩进的代码块简称 try 块,它里面放置的是可能引发异常的代码;
		except 关键字对应异常类型和处理该异常的代码块;
		多个 except 块之后可以放一个 else 块,表明程序不出现异常时还要执行 else 块;
		finally 块用于回收在 try 块里打开的物理资源,异常机制会保证 finally 块总被执行;
		raise 用于引发一个实际的异常,raise 可以单独作为语句使用,引发一个具体的异常对象;
"""
异常处理机制:
    else:没有异常时执行的内容
    finally:总会执行的内容
"""
try:
    a=1
    print(b)
except NameError as e :
    print('0-name error')
except KeyError as e :
    print('4-key error')
except Exception as e:
    print('1-exception')
else:
    print('2-noerror')
finally:
    print('3-run code')
##结果
0-name error
3-run code

3. Trigger exception

- Python 允许程序自行引发异常,自行引发异常使用 raise 语句来完成。
	raise语句中 Exception 是异常的类型(例如,NameError)参数标准异常中任一种,
	args 是自已提供的异常参数。
		raise [Exception [, args [, traceback]]]

Insert picture description here

age = int(input('age:'))
if 0<age<150:
    print(age)
else:
    #抛出异常
    raise ValueError('年龄必须在0-150之间')

4. Custom Exception

4.1 Use of custom exceptions

-	 用户自定义异常都应该继承 Exception 基类或 Exception 的子类,在自定义异常类时基本不需要书写
  更多的代码,只要指定自定义异常类的父类即可。
class AgeError(ValueError):
    pass
age = int(input('age:'))
if 0<age<150:
    print(age)
else:
    #抛出异常
    raise AgeError('年龄必须在0-150之间')
"""
结果
    raise AgeError('年龄必须在0-150之间')
__main__.AgeError: 年龄必须在0-150之间
"""

4.2 Python exception usage specification

- 	不要过度使用异常
	不要使用过于庞大的 try 块
	不要忽略捕获到的异常

Guess you like

Origin blog.csdn.net/qwerty1372431588/article/details/113741872
Recommended