2015-11-04 55 views
0

正在开发一个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 

到目前为止,其在打印我exception.now希望每当这个例外时我的程序把客户ID作为输入信息。该过程应该迭代直到用户输入有效的custid。

+0

这不是Python,所以我怀疑它运行。 – jonrsharpe

+0

它的运行成功,为了更好地理解我编写了简单的代码.i已经在其他文件中创建了alll所需的类。 –

+0

但您的*“简单代码”*不是有效的Python。给一个有机会跑步的[mcve]! – jonrsharpe

回答

1

你应该使用try-除非else语句块:

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

1

你会想尝试除了块。

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

+0

是的。我知道这一点。但在exceltions except子句中,我想再次调用该函数,该函数抛出异常,直到它接受有效的input.i.e。如果用户输入无效的custid,它应该抛出异常。打印该消息,并自行调用,直至获得来自客户的有效输入。 –

+0

@BhushanGadekar也许这样:将try块封装在一个检查标志的while循环中。在循环的开始将标志设置为false。如果异常触发,请将该标志设置为true。 – personjerry