zoukankan      html  css  js  c++  java
  • 学习心得2020.08.30

    032异常处理

    file_name=input('请输入需要打开的文件名:')
    f=open(file_name)
    print('文件的内容是:')
    for each_line in f:
        print(each_line)
    

    >>> my_list=['小甲鱼是帅哥']
    >>> assert len(my_list)>0
    >>> my_list.pop()
    '小甲鱼是帅哥'
    >>> assert len(my_list)>0
    Traceback (most recent call last):
      File "<pyshell#3>", line 1, in <module>
        assert len(my_list)>0
    AssertionError
    >>> my_list.fishc
    Traceback (most recent call last):
      File "<pyshell#4>", line 1, in <module>
        my_list.fishc
    AttributeError: 'list' object has no attribute 'fishc'
    >>> my_list=[1,2,3]
    >>> my_lsit[3]
    Traceback (most recent call last):
      File "<pyshell#6>", line 1, in <module>
        my_lsit[3]
    NameError: name 'my_lsit' is not defined
    >>> my_list[2]
    3
    >>> my_dict={'one':1,'two':2,'three':3}
    >>> my_dict['one']
    1
    >>> my_dict['two']
    2
    >>> my_dict['four']
    Traceback (most recent call last):
      File "<pyshell#11>", line 1, in <module>
        my_dict['four']
    KeyError: 'four'
    >>> 1+'1'
    Traceback (most recent call last):
      File "<pyshell#12>", line 1, in <module>
        1+'1'
    TypeError: unsupported operand type(s) for +: 'int' and 'str'
    

    033异常检测

    • try-except语句
      try:
      检测范围
      except Exception[as reason]:
      出现异常(Exception)后的处理代码
    try:
        sum=1+'1'
        f=open('我为什么是一个文件.txt')
        print(f.read())
        f.close()
    except OSError as reason:
        print('文件出错啦,出错的原因是:'+str(reason))
    except TypeError as reason:
        print('类型出错啦,出错的原因是:'+str(reason))
    
    • try-finally语句
      try:
      检测范围
      except Exception[as reason]:
      出现异常(Exception)后的处理代码
      finally:
      无论如何都会被执行的代码
    try:
        f=open('我为什么是一个文件.txt','w')
        print(f.write('我存在了!'))
        sum=1+'1'
    except (OSError,TypeError):
        print('文件出错啦')
    finally:
        f.close()
    
    • raise语句
      可以在其中添加解释异常原因的语句
    >>> raise ZeroDivisionError('除数为零的异常')
    Traceback (most recent call last):
      File "<pyshell#13>", line 1, in <module>
        raise ZeroDivisionError('除数为零的异常')
    ZeroDivisionError: 除数为零的异常
    
  • 相关阅读:
    606. Construct String from Binary Tree
    696. Count Binary Substrings
    POJ 3255 Roadblocks (次短路)
    POJ 2823 Sliding Window (单调队列)
    POJ 1704 Georgia and Bob (博弈)
    UVa 1663 Purifying Machine (二分匹配)
    UVa 10801 Lift Hopping (Dijkstra)
    POJ 3281 Dining (网络流之最大流)
    UVa 11100 The Trip, 2007 (题意+贪心)
    UVaLive 4254 Processor (二分+优先队列)
  • 原文地址:https://www.cnblogs.com/rioca/p/13627700.html
Copyright © 2011-2022 走看看