python try 和_try关键字和Python范例

python try 和

Python try关键字 (Python try keyword)

try is a keyword (case-sensitive) in python, it is a part of "try...except" block, it is used to define a block (of coding statements) to test/check whether this block contains an exception or not. If try block contains an exception program's control moves to the except block.

try是python中的一个关键字(区分大小写),它是“ try ... except”块的一部分,用于定义(编码语句的)块来测试/检查该块是否包含异常。 如果try块包含异常,程序的控制权将移至except块

Syntax of try keyword

try关键字的语法

    try:
        statement(s)-1
    except:
        statement(s)-2

While executing the statement(s)-1, if there is any exception raises, control jumps to except block and statement(s)-2 executes.

在执行语句-1时 ,如果引发任何异常,则控制跳转到块和语句2 除外

Example:

例:

    Input:
    a = 10
    b = 0

    try:
        # no error
        result = a%b
        print(result)
    
    except:
        print("There is an error")

    Output:
    There is an error

try关键字的Python示例 (Python examples of try keyword)

Example 1: Find modulus of two number and handle exception, if divisor is 0.

示例1:如果除数为0,则求两个数的模数并处理异常。

# python code to demonstrate example of 
# try, except keyword  

# Find modulus of two number and 
# handle exception, if divisor is 0

a = 10
b = 3

try:
    # no error
    result = a%b
    print(result)
    
    # assign 0 to b
    # an error will occur
    b = 0
    result = a%b
    print(result)
    
except:
    print("There is an error")

Output

输出量

1
There is an error


翻译自: https://www.includehelp.com/python/try-keyword-with-example.aspx

python try 和

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值