如何在处理异常后重新获得程序控制权?

How to gain program control back after handling the exception?

正在开发 python 应用程序。我已经从数据库中验证了客户 ID。意味着如果输入的 custid 存在于数据库中,我将引发异常。异常 class 我正在打印消息。到目前为止,它正在打印消息。但是我不确定如何将控制权返回到我正在输入的语句中。 主应用程序

Custid=input("enter custid)
Validate_custid(Custid) 
Print(Custid)

validate_custid 模块

From connections import cursor
From customExceptions import invalidcustidException
Def validate_custid(custid):
    Cursor.execute("select count(custid) from customer where custid=:custid",{"custid":custid}) 
    For row in cursor: 
        Count=row[0] 
        If Count==0: 
            Raise invalidcustidException

到目前为止它在 exception.now 中打印消息我希望我的程序在发生此异常时将 custid 作为输入。该过程应该迭代,直到用户输入有效的 custid。

你会想试一试 except block。

try:
  # portion of code that may throw exception
except invalidcuspidError:
  # stuff you want to do when exception thrown

有关更多信息,请参阅 https://docs.python.org/2/tutorial/errors.html

您正在尝试做的事情称为异常处理。我认为 Python 文档比我更能解释这一点,所以给你:https://docs.python.org/2/tutorial/errors.html#handling-exceptions

您应该使用带有 else 语句的 try-except 块:

while True:
    custid = input('Input custom Id: ')
    try:
        # Put your code that may be throw an exception here
        validate_custid(custid)
    except InvalidcustidException as err:
        # Handle the exception here
        print(err.strerror)
        continue # start a new loop
    else:
        # The part of code that will execute when no exceptions thrown
        print('Your custom id {} is valid.'.format(custid))
        break # escape the while loop

看这里:https://docs.python.org/3.4/tutorial/errors.html#handling-exceptions