Как я могу поймать только определенный тип ValueError в Python?

x = cumsum(c(0, runif(100, -1, +1)))
y = cumsum(c(0, runif(100, -1, +1)))
fit = lm(y ~ x)
> names(summary(fit))
[1] "call"          "terms"        
 [3] "residuals"     "coefficients" 
 [5] "aliased"       "sigma"        
 [7] "df"            "r.squared"    
 [9] "adj.r.squared" "fstatistic"   
[11] "cov.unscaled" 
    summary(fit)$r.squared
0
задан MaxS 18 January 2019 в 09:52
поделиться

2 ответа

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

Возможно, вам придется проверить, действительно ли e.args[0] содержит эту строку (спровоцируйте ошибку и напечатайте e.args[0])

См. Также документацию по BaseException.args [116 ]

0
ответ дан Michael Butscher 18 January 2019 в 09:52
поделиться

Вы можете поймать исключение ValueError следующим образом:

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]
0
ответ дан Loss of human identity 18 January 2019 в 09:52
поделиться
Другие вопросы по тегам:

Похожие вопросы: