【问题标题】:How to gain program control back after handling the exception?处理异常后如何重新获得程序控制?
【发布时间】:2015-11-04 00:57:23
【问题描述】:

正在开发一个 python 应用程序。我已经从数据库中验证了客户 ID。表示如果输入的 custid 存在于数据库中,我将引发异常。在异常类中,我正在打印消息。到目前为止,它正在打印消息。但我不知道如何让控制权回到我接受输入的语句。 主应用

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

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

【问题讨论】:

  • 那不是 Python,所以我怀疑它可以运行。
  • 它运行成功,为了更好地理解,我编写了简单的代码。我在其他文件中创建了所有需要的类。
  • 但是您的 "simple code" 不是有效的 Python。给一个有机会跑的minimal reproducible example
  • 看起来他只是将每一行的第一个字母大写。
  • 是的..对不起,我正在通过我的手机输入,所以忘记输入小写。模块很好。它的工作。我只是无法获得控制权。

标签: python database python-3.x custom-exceptions


【解决方案1】:

您应该使用带有 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

【讨论】:

    【解决方案2】:

    你会想要尝试除块。

    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 了解更多信息。

    【讨论】:

    • 是的。我知道。但是在exceltions except子句中,我想再次调用抛出异常的函数,直到它接受有效的输入。即如果用户输入无效的 custid,它应该抛出异常。打印消息,并在收到客户的有效输入之前调用自身。
    • @BhushanGadekar 也许是这样:将 try 块包装在一个检查标志的 while 循环中。在循环开始时将标志设置为 false。如果异常触发,则将该标志设置为 true。
    【解决方案3】:

    您尝试执行的操作称为异常处理。我认为 Python 文档比我更好地解释了这一点,所以你去:https://docs.python.org/2/tutorial/errors.html#handling-exceptions

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-07
      • 1970-01-01
      • 2010-11-06
      • 2015-07-12
      • 2017-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多