异常处理

异常处理 #

创建异常 #

异常使用 Exception 类进行表述。

Exception('something wrong')

抛出异常 #

可以使用关键字 raise 抛出异常。

raise Exception('something wrong')

异常处理 #

Python 异常处理的基本格式为:

try:
  <code may raise exception>
except <exception type>:
  <handle exception>
else:
  <handle when no exception>
finally:
  <executes whatever exception raised>

其中 finally 无论异常是否抛出都会被执行,也能够改变返回值。

def str2int(n):
    try:
        result = int(n)
        if result == 1:
            raise Exception('something wrong')
    except (ArithmeticError, TypeError) as error:
        print(error)
        return 0
    except Exception as error:
        print('exception: ', error)
        return 67
    else:
        print('no exception')
    finally:
        print('finally')
        return 300
沪ICP备17055033号-2