简体   繁体   中英

How can I catch only a certain type of ValueError in Python?

I process data and for some examples the data are problematic. Python raises a

ValueError: Residuals are not finite in the initial point.

Is there a possibility to catch Value errors only with the message "Residuals are not finite in the initial point." ? I tried:

try:
    [code that could raise the error]
except Exception as e:
    if e=='ValueError(\'Residuals are not finite in the initial point.\')':
        [do stuff I want when the Residuals are not finite]
    else:
        raise e

But it still raised the error all the time. Is there a way to achieve what I imagined?

Thanks

try:
    [code that could raise the error]
except ValueError as e:
    if len(e.args) > 0 and e.args[0] == 'Residuals are not finite in the initial point.':
        [do stuff I want when the Residuals are not finite]
    else:
        raise e

You may have to check if e.args[0] exactly contains this string (provoke the error and print e.args[0] )

See also documentation about BaseException.args

You can catch a ValueError Exception like this:

try:

    #[code that could raise the error]

except ValueError as e:

    print("Residuals are not finite in the initial point. ...")
    #[do stuff I want when the Residuals are not finite]

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