WoJ
WoJ

Reputation: 29993

How to target an Exception more accurately?

Consider the (compressed for the sake of example) code below:

import ics
import arrow
import requests

a = min(list(ics.Calendar(requests(get('http://asitewithcalendar.org').text).timeline.on(arrow.now())))

Quite a lot of things are happening here, I am fine with issues (connection, problems with the URL, ...) crashing the code but not with the following error:

ValueError: min() arg is an empty sequence

I would like to catch that specific error: the fact that what is provided to min() is an empty sequence (and pass on it). Even more specifically, I want the other exceptions to crash, including ValueError ones that are not related to the empty sequence fed to min().

A straightforward try catching ValueError would be fine for everything except the last constraint.

Is there a way to say "except ValueError when the error is min() arg is an empty sequence"?


Note: I know that the code in my example is ugly - I wrote it to showcase my question so if the only answer is "impossible - you have to rewrite it to pinpoint the line you want to try" then fine, otherwise I am looking for general solutions

Upvotes: 1

Views: 41

Answers (3)

Roharui
Roharui

Reputation: 100

how about this.

import numpy

a = min(list(ics.Calendar(requests(get('http://asitewithcalendar.org').text).timeline.on(arrow.now())) + [-np.inf])

when -inf has returned. list has nothing inside it.

Upvotes: 0

chepner
chepner

Reputation: 531480

This is a case where I would simply check the value before calling min rather than wait for an exception. There is no expression-level way to handle exceptions.

foo = list(ics.Calendar(requests(get('http://asitewithcalendar.org').text).timeline.on(arrow.now()))
if foo:
    a = min(foo)

It remains to decide what a should be if foo is empty, but you would have the same problem with a try statement:

foo = list(ics.Calendar(requests(get('http://asitewithcalendar.org').text).timeline.on(arrow.now()))

try:
    a = min(foo)
except ValueError:
    ???

I also wouldn't worry too much about only dealing with empty-sequence errors. Even if it is a different ValueError, a is just as undefined.

Upvotes: 0

Gustave Coste
Gustave Coste

Reputation: 707

You can do something like:

try:
   # Put your code to try here
   a = min(list(ics.Calendar(requests(get('http://asitewithcalendar.org').text).timeline.on(arrow.now())))

except ValueError as e:
    if str(e) == 'min() arg is an empty sequence':
        pass
    else:
        raise e

Upvotes: 2

Related Questions