简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM