这是我的代码中与该问题有关的部分:(我尽可能地减少了)
import os
import getpass
def PAUSE():
input("= Press <ENTER> to continue...")
def clearscreen():
os.system('cls' if os.name=='nt' else 'clear')
def loginscreen():
clearscreen()
print("==================================================================")
print("= LOGIN =")
print("==================================================================")
print("= None Important. =")
print("==================================================================")
username = input("= Please enter your username: ")
password = getpass.getpass("= Please enter the password that belongs to that username: ")
print("==================================================================")
try:
# I had too cut away the MariaDB Section for a MCVE, and thus i had to fill the dbusername and sdbpassword and isadmin, but without modifying relevant code. Thus i might have made a mistake in this array, dont use them alot sooo... if this were to occur i am sorry....
['dbusername = "stackoverflow", dbpassword = "stackoverflow", isadmin = "No"']
for row in results:
dbusername = row[0]
dbpassword = row[1]
isadmin = row [2]
if username == dbusername:
if password == dbpassword:
if isadmin == "Yes":
admin_main_menu()
elif isadmin == "No":
clearscreen()
main_menu()
########## For some reason the same problem arises when i use the commented away code under this comment.
# clearscreen()
# print("==============================================")
# print("= Unkown Username / Password =")
# print("==============================================")
# PAUSE()
# print("==============================================")
# loginscreen()
except:
clearscreen()
print("Failed to check codes. (Error: 5646FCJU), Contact N.S. Geldorp")
PAUSE()
def main_menu():
clearscreen()
print("=============================================")
print("= Main Menu =")
print("=============================================")
print("= 1. All unimportant... =")
print("= 5. Exit =")
print("=============================================")
answer = input("= Please enter the number of the function you wish to use: ")
print("=============================================")
clearscreen()
if answer == "1":
# print_animals()
print("Not needed")
PAUSE()
elif answer == "5":
# pass
print("Exiting...")
exit()
else:
print("Unimportant...")
PAUSE()
main_menu()
现在,我删除了所有内容,但可能除了登录屏幕和标准主菜单的相关部分。当然,暂停和清除屏幕功能始终会出现在相关功能中。至少是我写的。现在发生的事情是,当我成功登录后,我进入菜单,然后决定退出,它向我显示了除登录屏幕之外的错误……我不明白,是吗?
答案 0 :(得分:1)
这是演示1,442,633,它说明了为什么永远不要使用空白的except
子句。
sys.exit()
通过引发以下异常来工作:SystemExit
。通常,该异常一直一直到解释器,然后由解释器捕获并正常退出。但是因为您的try / except代码可以捕获所有内容,所以它也可以捕获所有内容。因此您会看到自己的错误消息,而不是解释器退出。
您应该只抓住您知道可以处理的事情。我不确定您期望该代码有哪些异常,但是大概它们是数据库代码引发的异常。您应该确定可以提出哪些建议,并只接受那些建议,例如except TypeError:
。
至少,您应该将您的除外限制为仅捕获实际错误,您可以使用except Exception:
进行操作; SystemExit从BaseException继承,BaseException是Exception的父类,所有其他运行时错误都从该父类继承。但是,您实际上不应该这样做,您应该只捕获特定于 的异常。
(还要注意,让for循环遍历数据库结果没有任何意义;我不明白您为什么这样做。)