zoukankan      html  css  js  c++  java
  • python__基础 : 异常处理与自定义异常

    异常处理方法一般为:

    try:
        ------code-----
    
    except Exception as e: # 抛出异常之后将会执行
        print(e)
    
    else:  # 没有异常将会执行
        print('no Exception')
    
    finally:  # 有没有异常都会执行
        print('execute is finish')

    可以用 raise 抛出一个异常,以下是一个输入字符太短的异常例子:

    class ShortInputException(Exception):
        '''自定义异常类'''
        def __init__(self, length, atleast):
            self.length = length
            self.atleast = atleast
    
    try:
        s = input('please input:')
        if len(s) < 3:
            raise ShortInputException(len(s), 3)
    except ShortInputException as e:
        print('输入长度是%s,长度至少是%s' %(e.length, e.atleast))
    else:
        print('nothing...')

    如果输入字符长度小于3,那么将会抛出 ShortInputException 异常:

    >>> please input:qw
        输入长度是2,长度至少是3 

    注意 如果异常处理时 再次 使用 raise 后面什么都没有,那么代表把这个异常还给系统,让解释器用默认的方式处理它.

  • 相关阅读:
    Spring 事务管理
    016 sleep,wait,yield,join区别
    013 GC机制
    011 CountDownLatch,CyclicBarrier和Semaphore
    012 public等关键字可见性
    010 JVM类加载
    009 JVM内存结构以及GC机制
    008 BlockingQueue理解
    python3 正则表达式
    python django
  • 原文地址:https://www.cnblogs.com/cccy0/p/9048723.html
Copyright © 2011-2022 走看看