zoukankan      html  css  js  c++  java
  • 7、Python异常

    本节主要介绍Python中异常处理的原理和主要的形式

    1、什么是异常

    Python中用异常对象来表示异常情况。程序在运行期间遇到错误后会引发异常。如果异常对象并未被处理或捕获,程序就会回溯终止执行。

    2、抛出异常

    raise语句,raise后面跟上Exception异常类或者Exception的子类,还可以在Exception的括号中加入异常的信息。

    >>>raise Exception('message')

    注意:Exception类是所有异常类的基类,我们还可以根据该类创建自己定义的异常类,如下:

    class SomeCustomException(Exception): pass

    3、捕捉异常(try/except语句

    try/except语句用来检测try语句块中的错误,从而让except语句捕获异常信息并处理。

    一个try语句块中可以抛出多个异常:

    1 try:
    2     x = input('Enter the first number: ')
    3     y = input('Enter the second number: ')
    4     print x/y
    5 except ZeroDivisionError:
    6     print "The second number can't be zero!"
    7 except TypeError:
    8     print "That wasn't a number, was it?"

    一个except语句可以捕获多个异常:

    1 try:
    2     x = input('Enter the first number: ')
    3     y = input('Enter the second number: ')
    4     print x/y
    5 except (ZeroDivisionError, TypeError, NameError):  #注意except语句后面的小括号
    6     print 'Your numbers were bogus...'

    访问捕捉到的异常对象并将异常信息打印输出:

    1 try:
    2     x = input('Enter the first number: ')
    3     y = input('Enter the second number: ')
    4     print x/y
    5 except (ZeroDivisionError, TypeError), e:
    6     print e

    捕捉全部异常,防止漏掉无法预测的异常情况:

    1 try:
    2     x = input('Enter the first number: ')
    3     y = input('Enter the second number: ')
    4     print x/y
    5 except :
    6     print 'Someting wrong happened...'

    4、else子句。除了使用except子句,还可以使用else子句,如果try块中没有引发异常,else子句就会被执行

     1 while 1:
     2     try:
     3         x = input('Enter the first number: ')
     4         y = input('Enter the second number: ')
     5         value = x/y
     6         print 'x/y is', value
     7     except:
     8         print 'Invalid input. Please try again.'
     9     else:
    10         break

    上面代码块运行后用户输入的x、y值合法的情况下将执行else子句,从而让程序退出执行。

    5、finally子句。不论try子句中是否发生异常情况,finally子句肯定会被执行,也可以和else子句一起使用。finally子句常用在程序的最后关闭文件或网络套接字

    1 try:
    2     1/0
    3 except:
    4     print 'Unknow variable'
    5 else:
    6     print 'That went well'
    7 finally:
    8     print 'Cleaning up'

    6、异常和函数

    如果异常在函数内引发而不被处理,它就会传递到函数调用的地方,如果一直不被处理,异常会传递到主程序,以堆栈跟踪的形式终止

    def faulty():
        raise Exception('Someting is wrong!')
    def ignore_exception():
        faulty()
        
    def handle_exception():
        try:
            faulty()
        except Exception, e:
            print 'Exception handled!',e
    
    handle_exception() 
    ignore_exception()

    在上面的代码块中,函数handle_exception()在调用faulty()后,faulty()函数抛出异常并被传递到handle_exception()中,从而被try/except语句处理。而ignare_exception()函数中没有对faulty()做异常处理,从而引发异常的堆栈跟踪。

    注意:条件语句if/esle可以实现和异常处理同样的功能,但是条件语句可能在自然性和可读性上差一些。

  • 相关阅读:
    LeetCode第三题:Longest Substring Without Repeating Characters
    LeetCode第二题:Add Two Numbers
    LeetCode第一题:Two Sum
    第五章 单体内置对象
    第五章 引用类型 基本包装类型
    第五章 引用类型 Function 类型
    第五章 引用类型 RegExp 类型
    第五章 引用类型 Date类型
    第五章 引用类型 Array类型
    第五章 引用类型 Object类型
  • 原文地址:https://www.cnblogs.com/wanghaoran/p/2983665.html
Copyright © 2011-2022 走看看