PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, November 14, 2022

[FIXED] How to fix "During handling of the above exception, another exception occurred: "

 November 14, 2022     error-handling, python, python-3.x, try-except, valueerror     No comments   

Issue

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.

code

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

errors

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'


Solution

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

Updated in response to comment, simply cast your string to an int like this then use int_number_of_books as the 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


Answered By - Dan-Dev
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing