[英]How to fix "During handling of the above exception, another exception occurred: "
How do i fix this error, whenever i enter data that should cause an exception more than once the program crashes.每当我输入的数据不止一次导致程序崩溃时,我该如何解决这个错误。 Here is my code and what it outputs, it should keep repeating until correct data is entered.这是我的代码及其输出的内容,它应该不断重复,直到输入正确的数据。
flag=False
while flag==False:
try:
number=int(input("Enter number of books: "))
except ValueError:
print("Please enter number of books as a positive whole number ")
number=int(input("Enter number of books: "))
else:
flag=True
Traceback (most recent call last):
File "C:\Users\Alex\OneDrive\Documents\ComputerScience\Intro2.py", line 5, in <module>
number=int(input("Enter number of books: "))
ValueError: invalid literal for int() with base 10: '3.3'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Alex\OneDrive\Documents\ComputerScience\Intro2.py", line 8, in <module>
number=int(input("Enter number of books: "))
ValueError: invalid literal for int() with base 10: '3.4' ValueError: int() 以 10 为底的无效文字:'3.4'
Try this it evaluates if your string is a digit, then breaks out of the look.试试这个,它会评估你的字符串是否是数字,然后打破外观。 Exception handling is expensive in computing terms and should be avoided where possible异常处理在计算方面是昂贵的,应尽可能避免
while True:
no_of_books = input("enter number of books")
if no_of_books.isdigit():
break
The reason your code didn't keep repeating was that it thew an exception on line 5 which was wrapped in the try block then in the except block it threw another exception on line 8 which was not wrapped in a try block so it terminated您的代码没有不断重复的原因是它在第 5 行出现异常,该异常被包装在 try 块中,然后在 except 块中它在第 8 行引发了另一个异常,该异常没有被包装在 try 块中,因此它终止了
Updated in response to comment , simply cast your string to an int like this then use int_number_of_books
as the int更新以响应评论,只需将您的字符串转换为这样的 int 然后使用int_number_of_books
作为 int
while True:
no_of_books = input("enter number of books")
if no_of_books.isdigit():
int_number_of_books = int(no_of_books)
break
if int_number_of_books <= 0:
# your code here
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.