异常处理
错误和异常
在高级编程语言中,一般都有错误和异常的概念,错误指逻辑错误,笔误,函数或类使用错误,总之错误是可以避免的,异常就是没有错误的前提下出现的意外,异常时可以捕获并处理的。
raise语句
1 raise BaseException
直接抛出BaseException
异常捕获
1 try: 2 1/0 3 print(a) 4 except ZeroDivisionError as e: # as后是前的标识符 5 print(type(e), e) 6 except NameError as e: 7 print(type(e), e) 8 else: 9 print('OK') # 没有捕获错误时执行 10 finally: 11 print('finally') # finally必定执行 12 # <class 'ZeroDivisionError'> division by zero 13 # finally
1 try: 2 print(a) 3 1/0 4 except ZeroDivisionError as e: # as后是前的标识符 5 print(type(e), e) 6 except NameError as e: 7 print(type(e), e) 8 else: 9 print('OK') # 没有捕获错误时执行 10 finally: 11 print('finally') # finally必定执行 12 # <class 'NameError'> name 'a' is not defined 13 # finally
1 a = 1 2 try: 3 print(a) 4 except ZeroDivisionError as e: # as后是前的标识符 5 print(type(e), e) 6 except NameError as e: 7 print(type(e), e) 8 else: 9 print('OK') # 没有捕获错误时执行 10 finally: 11 print('finally') # finally必定执行 12 # 1 13 # OK 14 # finally
except: 可以捕获所有异常,但是尽量使用精确异常捕获
KeyboardInterrupt 在命令行界面捕捉“Ctrl+C”终止命名错误提示
argparse模块
1 import argparse 2 parser = argparse.ArgumentParser(prog='ls', add_help=True, description='list directory contents') # add_help开启-p,--help命令 3 parser.add_argument('path', nargs='?', default='.', help='directory') # path缺省为当前目录'.',可以在命令行界面自定义目录 4 parser.add_argument('-a', '--all', action='store_true', help='show all files, do not ignore entries starting with .') 5 parser.add_argument('-l', action='store_true', help='use a long listing format') 6 args = parser.parse_args() # Namespace(all=False, l=False, path='.') 7 parser.print_help() 8 # usage: ls [-h] [-a] [-l] [path] 9 # 10 # list directory contents 11 # 12 # positional arguments: 13 # path directory 14 # 15 # optional arguments: 16 # -h, --help show this help message and exit 17 # -a, --all show all files, do not ignore entries starting with . 18 # -l use a long listing format
在命令行界面执行py文件可以记录-a,-l命令的True,False开关状态