zoukankan      html  css  js  c++  java
  • 《Python基础教程》要点(八):异常

    概要:

    一、异常

    二、按自己的方式出错。

    二、捕捉异常

    三、except子句

    四、用一个块捕捉两个异常

    五、捕捉对象

    一、异常

    常常为了能够处理异常事件(比如除0),可以在所有可能发生这类事件的地方都使用条件语句,这样没效率、不灵活。想直接忽略这些异常事件,期望它们永不发生,Python的异常对象提供了非常强大的替代解决方案。

    Python用异常对象(exception object)来表示异常情况。遇到错误,会引发异常。如果异常对象并未被处理或捕捉,程序就会用所谓的回溯(Traceback,一种错误信息)终止执行。

    每个异常都是一些类的实例。

    二、按自己的方式出错。

    异常可以在某些东西出错时自动引发。

    我们自己也可以引发异常--创建自己的异常类型:

    1、raise 语句

    引发异常,可以使用一个类(应该是Exception的子类)或者实例参数调用raise语句。使用类时,程序会自动创建实例。

    使用内建的Exception异常类

    >>> raise Exception
    
    Traceback (most recent call last):
      File "<pyshell#0>", line 1, in <module>
        raise Exception
    Exception
    
    
    >>> raise Exception('you fogot to do something before!') #添加错误信息
    
    Traceback (most recent call last):
      File "<pyshell#1>", line 1, in <module>
        raise Exception('you fogot to do something before!') #添加错误信息
    Exception: you fogot to do something before!
    >>> 

    关于内建异常类可参Python库参考手册的“Built-Exceptions”。
    可以使用 dir 函数列出exceptions模块的内容:

    >>> import exceptions
    >>> dir(exceptions)
    ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'EnvironmentError', 'Exception', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__doc__', '__name__', '__package__']

    所有这些异常都可以在raise语句中:

    >>> raise ArithmeticError
    
    Traceback (most recent call last):
      File "<pyshell#4>", line 1, in <module>
        raise ArithmeticError
    ArithmeticError

     

    2、自定义异常类

    想要使用特殊的错误代码处理某错误,就需要一个独立于exceptions模块的异常类。

    基本上如下:

    >>> class SomeCustomException(Exception):
        pass

    二、捕捉异常

    诱捕(捕捉)异常:处理异常。

    >>> try:
        x = input('Enter the first number: ')
        y = input('Enter the second number: ')
        print x/y
    except ZeroDivisionError:
        print "The second number can't be zero ! "
    
        
    Enter the first number: 3
    Enter the second number: 0
    The second number can't be zero ! 

    【注意】如果没有捕捉异常,它就会被“传播”到调用函数中。如果在那里依然没有捕获,这些异常就会“浮”到程序的最顶层。也就是说你可以捕捉到其他人的函数中所引发的异常。

    如果捕捉到异常,又想重新引发它(传递异常),可以调用不带参的raise。

    三、except子句

    四、用一个块捕捉两个异常

    五、捕捉对象

  • 相关阅读:
    Two Sum II
    Subarray Sum
    Intersection of Two Arrays
    Reorder List
    Convert Sorted List to Binary Search Tree
    Remove Duplicates from Sorted List II
    Partition List
    Linked List Cycle II
    Sort List
    struts2结果跳转和参数获取
  • 原文地址:https://www.cnblogs.com/dadada/p/3077635.html
Copyright © 2011-2022 走看看