如何使用 try 和 except

时间:2021-04-06 04:08:50

标签: python exception try-catch

hours_work = float(input("How many hours do you work? "))
pay_rate = float(input("How much do you earn per hour? "))
print("You get paid:", hours_work * pay_rate)

try:
  (ten)
except Exception:
  Print(" ten ")

print("That's not a number")

在尝试计算工资率时,我对 try 和 except 的工作方式感到困惑。

4 个答案:

答案 0 :(得分:1)

try-except 用于可能出错的情况。在您的情况下,用户可以为其中一个输入输入无效数字,例如 'a' 或其他一些非数字字符。在这种情况下您无法进行计算,这正是异常的用途。

try:
    hours_work = float(input("How many hours do you work? "))
    pay_rate = float(input("How much do you earn per hour? "))
    print("You get paid:", hours_work * pay_rate)
except ValueError:
    print('You have to enter a number for this to work.')

如果您不想使用 print,则 try 语句必须出现在 else 块中。如果你把它放在 except 之后,即使有错误它也会被执行,并在这种情况下导致另一个错误。

答案 1 :(得分:1)

这里是一个部分简化的示例,为您指明正确的方向并介绍相关的 tryexceptelse 异常处理构造。

示例:

while True:
    
    hours_worked_str = input("How many hours did you work? ")
    
    # Perform operation that may trigger an exception in try block
    try:
        hours_worked = float(hours_worked_str)

    # If the anticipated exception occurred, handle it
    except ValueError as exc:
        print(exc)
        print("Please try again.")

    # If no exception occurred move on
    else:
        break

print(f"You worked {hours_worked} hours.")

答案 2 :(得分:0)

try:
    'I\'m trying to run my body code'
    pass
except:
    'I am activated when the "try" error occurs'
    pass

“除外”状态:

except:
Runs at the time of each error

except ErrorName:
When you only want to run at a specific time error

except ErrorName as value:
When you want to get the cause of the error in the form of a string

答案 3 :(得分:0)

错误会暂停您的程序执行。还想继续吗?使用 tryexcept

这在很多情况下都很有用,我能想到的就是计算器。如果您的用户除以零或任何会使他们陷入数学监狱的事情,那么您可能希望向他们显示一条消息,告诉他们您不能这样做。把你的计算代码放在try里面,以及catch`中发生异常时要调用的代码。