开发者社区 问答 正文

python怎么处理错误和异常

问题来源于python学习网

展开
收起
保持可爱mmm 2019-12-10 15:48:34 467 分享 版权
1 条回答
写回答
取消 提交回答
  • 异常

    当你的程序出现例外情况时就会发生异常(Exception)。例如,当你想要读取一个文件时,而那个文件却不存在,怎么办?又或者你在程序执行时不小心把它删除了,怎么办?这些通过使用异常来进行处理。类似地,如果你的程序中出现了一些无效的语句该怎么办?Python 将会对此进行处理,举起(Raises)它的小手来告诉你哪里出现了一个错误(Error)。

    错误

    你可以想象一个简单的 print 函数调用。如果我们把 print 误拼成 Print 会怎样?你会注意到它的首字母是大写。在这一例子中,Python 会抛出(Raise)一个语法错误。

    Print("Hello World") Traceback (most recent call last): File " ", line 1, in NameError: name 'Print' is not defined >>> print("Hello World") Hello World

    你会注意到一个 NameError 错误被抛出,同时 Python 还会打印出检测到的错误发生的位置。这就是一个错误错误处理器(Error Handler)2 为这个错误所做的事情。

    异常

    我们将尝试(Try)去读取用户的输入内容。按下 [ctrl-d] 来看看会发生什么事情。

    s = input('Enter something --> ') Enter something --> Traceback (most recent call last): File " ", line 1, in EOFError

    此处 Python 指出了一个称作 EOFError 的错误,代表着它发现了一个文件结尾(End of File)符号(由 ctrl-d 实现)在不该出现的时候出现了。

    处理异常

    我们可以通过使用 try..except 来处理异常状况。一般来说我们会把通常的语句放在 try 代码块中,将我们的错误处理器代码放置在 except 代码块中。

    案例(保存文 exceptions_handle.py):

    try: text = input('Enter something --> ') except EOFError: print('Why did you do an EOF on me?') except KeyboardInterrupt: print('You cancelled the operation.') else: print('You entered {}'.format(text))

    输出

    Press ctrl + d

    $ python exceptions_handle.py Enter something --> Why did you do an EOF on me?

    Press ctrl + c

    $ python exceptions_handle.py Enter something --> ^CYou cancelled the operation.

    $ python exceptions_handle.py Enter something --> No exceptions You entered No exceptions

    2019-12-10 15:48:42
    赞同 展开评论