zoukankan      html  css  js  c++  java
  • Python学习之路:异常处理

    参考链接:http://www.cnblogs.com/wupeiqi/articles/5017742.html

    -----异常处理

     1 names = ['alex','jack']
     2 data = {}
     3 try:
     4     # names[3]
     5     # data['name']
     6     open("tes.txt")
     7 # except Exception as e:#抓住所有错误,具体哪个错误自己揣测,一般不建议最开始用,不便于调试
     8 #     print("出错了",e)
     9 except (KeyError,IndexError) as e :#合在一起写代码简单,但是不知道哪个出错了
    10     print("没有这个Key",e)#适用场景:两种错误均采用统一的处理办法
    11 
    12 except IndexError as e :
    13     print("列表操作错误",e)
    14 
    15 except Exception as e:#最后可以用
    16     print("未知错误",e)
    17 
    18 else:
    19     print("一切正常")
    20 
    21 finally:
    22     print("不管有没有错,都执行")
    23 
    24 #-------- value error------------------
    25 s1 = 'hello'
    26 try:
    27     int(s1)
    28 except ValueError as e:
    29     print ("粗错啦",e)
    View Code

    -----自定义异常

     1 class AlexException(Exception):
     2 
     3     def __init__(self, msg):
     4         self.message = msg
     5 
     6     # def __str__(self):
     7     #     return self.message
     8 
     9 try:
    10     raise AlexException('数据库连不上')
    11 except AlexException as e:
    12     print(e)
    View Code
  • 相关阅读:
    go语言的运行时支持到底是多线程还是单线程
    丑数
    把数组排成最小数
    连续子数组的最大和
    最小的k个数
    数组中出现次数超过一半的数字
    字符串的排序
    二叉搜索树与双向链表
    复杂链表的赋值
    二叉树中和为某一值的路径
  • 原文地址:https://www.cnblogs.com/xiaobai005/p/8460965.html
Copyright © 2011-2022 走看看