标签:strip() theme one 比较 无法 容错 信号 技术 工作
def test(): print(‘test running‘) choice_dic={ ‘1‘:test } while True: choice=input(‘>>: ‘).strip() if not choice or choice not in choice_dic:continue #这便是一种异常处理机制啊 choice_dic[choice]()
try: 被检测的代码块 except 异常类型: try中一旦检测到指定的异常类型,则执行此位置的逻辑代码
s1 = ‘hello‘ try: int(s1) except IndexError as e: print(e) 运行结果: Traceback (most recent call last): File "J:/Python_Project/day09/练习/123.py", line 77, in <module> int(s1) ValueError: invalid literal for int() with base 10: ‘hello‘
s1 = ‘hello‘ try: int(s1) except Exception as e: print(e) 运行结果: invalid literal for int() with base 10: ‘hello‘
s1 = ‘hello‘ try: int(s1) except IndexError as e: print(e) except KeyError as e: print(e) except ValueError as e: print(e) except Exception as e: # 可以在最后,来一个万能异常 print(e)
s1 = ‘hello‘ try: int(s1) except IndexError as e: print(e) except KeyError as e: print(e) except ValueError as e: print(e) #except Exception as e: # print(e) else: print(‘try内代码块没有异常则执行我‘) finally: print(‘无论异常与否,都会执行该模块,通常是进行清理工作‘)
#_*_coding:utf-8_*_ try: raise TypeError(‘类型错误‘) except Exception as e: print(e) 运行结果: 类型错误
#_*_coding:utf-8_*_ __author__ = ‘Linhaifeng‘ class EgonException(BaseException): def __init__(self,msg): self.msg=msg def __str__(self): return self.msg try: raise EgonException(‘类型错误‘) except EgonException as e: print(e)
#_*_coding:utf-8_*_ #if方式处理异常 # num1=input(‘>>: ‘) #输入一个字符串试试 # if num1.isdigit(): # int(num1) #我们的正统程序放到了这里,其余的都属于异常处理范畴 # elif num1.isspace(): # print(‘输入的是空格,就执行我这里的逻辑‘) # elif len(num1) == 0: # print(‘输入的是空,就执行我这里的逻辑‘) # else: # print(‘其他情情况,执行我这里的逻辑‘) #第二段代码 # num2=input(‘>>: ‘) #输入一个字符串试试 # int(num2) #第三段代码 # num3=input(‘>>: ‘) #输入一个字符串试试 # int(num3) #try..except..方式处理 try: #第一段代码 num1=input(‘>>: ‘) #输入一个字符串试试 int(num1) #我们的正统程序放到了这里,其余的都属于异常处理范畴 #第二段代码 num2=input(‘>>: ‘) #输入一个字符串试试 int(num2) #第三段代码 num3=input(‘>>: ‘) #输入一个字符串试试 int(num3) except ValueError as e: print(e)
标签:strip() theme one 比较 无法 容错 信号 技术 工作
原文地址:http://www.cnblogs.com/xiaofeiweb/p/7131376.html