• 错误和异常86


     1 # while True: print('Hello World!')
     2 print('异常有不同的类型,这些类型都作为信息的一部分打印出来:以下例子中的类型有ZeroDivisiongError,NameError和TypeError')
     3 # print(10*(1/0))
     4 
     5 # print(4+spam*3)
     6 
     7 # print('2'+2)
     8 
     9 print('Enter a number,if not give a exception')
    10 while True:
    11     try:
    12         str = int(input('Please enter a number'))
    13         # break
    14     except ValueError:
    15         print('Oops,That was no valid number .Try again ')
    16 
    17 print('except(RuntimeError,ValueError,TypeError,NameError)')
    18 import sys
    19 try:
    20 
    21     f = open('E:\foo.txt')
    22     s = f.readline()
    23     i = int(s.strip())
    24 except OSError as err:
    25     print('OS error:{}'.format(err))
    26 
    27 except ValueError:
    28     print('Could not conver a data to a integer.')
    29 except:
    30     print('Unexpected error:',sys.exc_info()[0])
    31     raise
    32 
    33 print('example2----------------------------------------------------------')
    34 import sys
    35 for foo in sys.argv[1:]:
    36     try:
    37         f = open(foo,'r')
    38     except IOError:
    39         print('cannot open',foo)
    40     else:
    41         print(foo,'has',len(f.readlines()),'lines')
    42         f.close()
    43 
    44 print('heheda-------------------------------------')
    45 def this_fails():
    46     x = 1/0
    47 try:
    48     this_fails()
    49 except ZeroDivisionError as err:
    50     print('Handling run-time error:',err)
    51 
    52 print('hehda-------------------------------------')
    53 raise NameError('HiThere')
    54 try:
    55     raise NameError('HiThere')
    56 except NameError:
    57     print('An exception flew by!')
    58     raise
    59 
    60 print('hehda----------------------------------------------')
    61 class MyError(Exception):
    62     def __init__(self,value):
    63         self.value = value
    64     def __str__(self):
    65         return repr(self.value)
    66 try:
    67     raise MyError(2*2)
    68 except MyError as e:
    69     print('My exception occurred,value:'.format(e.value))
    70 
    71 print('hehda----------------------------------------------')
    72 
    73 
    74 class MyError(Exception):
    75     def __init__(self, value):
    76         self.value = value
    77 
    78     def __str__(self):
    79         return repr(self.value)
    80 
    81 try:
    82     raise MyError(2 * 2)
    83 except MyError as e:
    84     print('My exception occurred,value:'.format(e.value))
    85 
    86 raise MyError('oops!')
  • 相关阅读:
    yii修改密码 弹出修改成功提示(八)
    yii模型规则的简单使用以及开启前端的验证(七)
    利用ab测试并发可靠么
    yii数据库链接(六)
    初始化collectionViewCell
    监听事件
    ControllerEvent
    代码构建视图
    DeveloperAppleHelp
    Xcode 小技巧
  • 原文地址:https://www.cnblogs.com/jpr-ok/p/9244734.html
Copyright © 2020-2023  润新知