Skip to content

异常处理 #11

Description

@eziceice

Exception

  • Python用异常对象(exception object)来表示异常情况.遇到错误后,会引发异常,如果异常对象没有被捕捉或者处理,程序就会用所谓的回溯(traceback,一种错误信息)终止执行-类似于Java中的stacktrace. 自定义异常类只要继承自exception就可以了.
raise Exception('test')

import exceptions
dir(exceptions) #列出python中所有种类的异常

class CustomException(Exception): #自定义异常继承自Exception
pass
  • 捕捉异常使用try/except语句来实现.
try:
    x = input('1: ')
    y = input('2: ')
    print(x/y)
except ZeroDivisionError:
    print('1234')
  • 如果捕捉到了异常,但是又想重新引发它(抛出异常或者传递异常),那么可以调用不带任何参数的raise. 同时,可以添加多个语句捕捉到多种异常.也可以用一个块捕捉多个异常.
try:
    x = input('1: ')
    y = input('2: ')
    print(x/y)
except ZeroDivisionError:
    raise 
except TypeError:
    raise
except (ZeroDivisionError, TypeError, NameError):
    raise
except (ZeroDivisionError, TypeError, NameError) as e: #捕捉异常并在console中输出
    print(e)
except: #捕捉全部异常,但需要谨慎使用,有时候有些错误会被忽略
    print('error')
except Exception as e: #用这个except捕捉全部异常好一些
    print(e)
  • try/except可以和else一起使用.只有当exception不被触发的时候,else语句才会被调用.
try:
    print('123')
except:
    print('456')
else:
    print('bye')
  • finally可以放在try/except最后,finally中的语句将在异常发生或者不发生的情况下都会被执行.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions