What exceptions can conversion functions raise?

Discuss API design here.
User avatar
iPlayer
Developer
Posts: 590
Joined: Sat Nov 14, 2015 8:37 am
Location: Moscow
Contact:

What exceptions can conversion functions raise?

Postby iPlayer » Mon Jan 04, 2016 2:21 pm

According to Ayuto's announcement, it's only ValueError:

If the conversion failed, a ValueError will be raised.


But I found the following try-except statements in players/weapons/__init__.py:

Syntax: Select all

try:
index = index_from_inthandle(handle)
except (ValueError, OverflowError):
continue


Looking at C++ code, there's no explicit OverflowError, too. Only ValueError.

Question is, where does OverflowError come from? Should I always be ready to catch it?
User avatar
Ayuto
Project Leader
Posts: 2193
Joined: Sat Jul 07, 2012 8:17 am
Location: Germany

Postby Ayuto » Mon Jan 04, 2016 9:07 pm

I hope this answers your question:

Syntax: Select all

from players.helpers import userid_from_inthandle


# Exception raised by SP:

# ValueError:
# Raised if the conversion failed
userid_from_inthandle(123456789)


# Exception raised by the internals of Boost.Python:

# Boost.Python.ArgumentError:
# Raised if you pass the wrong type to a function.
# Catch it by using TypeError. It's the ArgumentError's base class.
userid_from_inthandle('a')

# OverflowError:
# Raised when you pass a signed integer to a function that requires an
# unsigned integer. TBH, this should be an ArgumentError/TypeError/ValueError as well.
userid_from_inthandle(-1)

Edit:

  • You don't need to catch ArgumentErrors. Those should probably happen.
  • Catch OverflowErrors if the function requires unsigned integers and you know that the value can be a signed integer.
User avatar
iPlayer
Developer
Posts: 590
Joined: Sat Nov 14, 2015 8:37 am
Location: Moscow
Contact:

Postby iPlayer » Mon Jan 04, 2016 9:26 pm

Thanks, Ayuto, now I get it.

I asked because I decided to make a pull request to entities/specials.py and that required me to know what exceptions I want to suppress.
Hope I didn't mess this up.

Edit: Well, I did mess this up. Thought that index_from_inthandle accepted signed ints. Now it's 2 commits.

Return to “API Design”

Who is online

Users browsing this forum: No registered users and 20 guests