python 例外 重试_Python例外:简介

python 例外 重试

A Python program terminates as soon as it encounters an error. In Python, an error can be a syntax error or an exception. In this article, you will see what an exception is and how it differs from a syntax error. After that, you will learn about raising exceptions and making assertions. Then, you’ll finish with a demonstration of the try and except block.

Python程序在遇到错误后立即终止。 在Python中,错误可以是语法错误或异常。 在本文中,您将看到什么是异常以及异常与语法错误的区别。 之后,您将学习有关引发异常和声明的知识。 然后,您将完成try和except块的演示。

intro_exceptions

Free PDF Download: Python 3 Cheat Sheet

免费PDF下载: Python 3备忘单

异常与语法错误 (Exceptions versus Syntax Errors)

Syntax errors occur when the parser detects an incorrect statement. Observe the following example:

当解析器检测到不正确的语句时,就会发生语法错误。 观察以下示例:

 >>> print( 0 / 0 ))
  File >>> print( 0 / 0 ))
  File "<stdin>", line "<stdin>" , line 1
    1
    printprint ( ( 0 0 / / 0 0 ))
                  ))
                  ^
^
SyntaxError: SyntaxError : invalid syntax
invalid syntax

The arrow indicates where the parser ran into the syntax error. In this example, there was one bracket too many. Remove it and run your code again:

箭头指示解析器在哪里遇到语法错误 。 在此示例中,一个括号过多。 删除它并再次运行代码:

This time, you ran into an exception error. This type of error occurs whenever syntactically correct Python code results in an error. The last line of the message indicated what type of exception error you ran into.

这次,您遇到了异常错误 。 只要语法正确的Python代码导致错误,就会发生此类错误。 消息的最后一行指示您遇到的异常错误类型。

Instead of showing the message exception error, Python details what type of exception error was encountered. In this case, it was a ZeroDivisionError. Python comes with various built-in exceptions as well as the possibility to create self-defined exceptions.

Python没有显示消息exception error ,而是详细介绍了遇到的异常错误类型。 在这种情况下,这是一个ZeroDivisionError 。 Python带有各种内置的异常以及创建自定义异常的可能性。

引发异常 (Raising an Exception)

We can use raise to throw an exception if a condition occurs. The statement can be complemented with a custom exception.

如果条件发生,我们可以使用raise引发异常。 该语句可以补充自定义异常。

exceptions_raise

If you want to throw an error when a certain condition occurs using raise, you could go about it like this:

如果您想在某些情况下使用raise引发错误,可以这样处理:

 x x = = 10
10
if if x x > > 55 :
    :
    raise raise ExceptionException (( 'x should not exceed 5. The value of x was: {}''x should not exceed 5. The value of x was: {}' .. formatformat (( xx ))
))

When you run this code, the output will be the following:

当您运行此代码时,输​​出将为以下内容:

The program comes to a halt and displays our exception to screen, offering clues about what went wrong.

该程序停止运行,并在屏幕上显示我们的异常,从而提供了有关错误原因的线索。

AssertionError异常

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值