Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unable to Catch Exception and Raise Error in Python

Suppose that I have a variable initial_cash = 'a'. I want to check if this is convertible to float else I want to raise error for that I’ve written code below:

initial_cash = 'a'
try:
    initial_cash = float(initial_cash)
except TypeError:
    raise TypeError("Initial cash amount should be float or int")

I am unable to raise exception instead I get ValueError: could not convert string to float: 'a'. What am I doing wrong due to which the expectation is not caught?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your answer is in the error message – ValueError. you should expect ValueError instead of TypeError.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading