zoukankan      html  css  js  c++  java
  • python学习 (三十二) 异常处理

    1 异常:

    def exceptionHandling():
        try:
            a = 10
            b = 0
            d = a / b
            print(d)
        except ZeroDivisionError as ex:
            print("exception 1 " + str(ex) )
        except BaseException as ex:
            print("exception 2 " + str(ex))
    
    exceptionHandling()

    2 : else(如果没有异常)

    def exceptionHandling():
        try:
            a = 10
            b = "d"
            d = a / b
            print(d)
        except ZeroDivisionError as ex:
            print("exception 1 " + str(ex) )
        except BaseException as ex:
            print("base exception")
        else:                          // 如果没有上面两个异常,会走到这里
            print("OK")
    
    exceptionHandling()

     3:Finally

    def exceptionHandling():
        try:
            a = 10
            b = 5
            d = a / b
            print(d)
        except ZeroDivisionError as ex:
            print("exception 1 " + str(ex) )
        except BaseException as ex:
            print("base exception")
        else:
            print("OK")
        finally:                          // 无论有无异常,都会执行
            print("must execute")
    
    exceptionHandling()

     4: 抛出异常

      raise  XXXX

    def exceptionHandling():
        try:
            a = 10
            b = 0
            d = a / b
            print(d)
        except ZeroDivisionError as ex:
            print("exception 1 " + str(ex) )
            raise ZeroDivisionError("aaaaaaaaaaaa")                 // 可以在代码里面抛出异常
        except BaseException as ex:
            print("base exception")
        else:
            print("OK")
        finally:
            print("must execute")
    
    exceptionHandling()

     

  • 相关阅读:
    cuda(2)---方阵乘法
    cuda(1)-imageBlur
    python(6) 字符串操作
    CUDA 编程之Release模式和Debug模式
    20200909 day4 刷题记录
    20200908 day3 刷题记录
    20200906 day1 模拟(一)
    刷题Day 4-6 树形dp三题
    4.28 刷题Day 3 树形dp一题
    DTQ2019-D1T2 括号树 题解
  • 原文地址:https://www.cnblogs.com/liufei1983/p/9865999.html
Copyright © 2011-2022 走看看