19

I'm looking at Python's built-in exceptions and wondering what the closest equivalent of Java's UnsupportedOperationException is. NotImplementedError is close but seems to suggest something slightly different. Should I be using RuntimeError or implementing my own Exception?

erwaman
  • 3,307
  • 3
  • 28
  • 29
  • 1
    I'd say they mean the same thing, using different words. It is not supported because it hasn't been implemented, and it wasn't implemented because it's not supported. It just depends on your point of view, i.e. the intent. – Andreas Jun 28 '16 at 03:41
  • @Andreas That's a good way to look at it. I guess I can explain in the error message why the method is not implemented. – erwaman Jun 28 '16 at 03:58

3 Answers3

15

The closest equivalent is to simply not implement the unsupported method. The resulting exception if you try to use the nonexistent method is an AttributeError.

user2357112
  • 260,549
  • 28
  • 431
  • 505
  • 3
    @gotnull: Because it answers the question. – user2357112 Jun 28 '16 at 03:45
  • 1
    I'd like to define the method and have a body that's just `raise ` and in the exception message explain why the method should not be implemented/supported. I'm afraid that if I don't do this, someone may try to implement the method in the future without understanding why it was not implemented originally. – erwaman Jun 28 '16 at 03:57
  • 1
    @erwaman So raise an `AttributeError`. Or raise your own custom exception type if you'd rather. – dimo414 Jun 28 '16 at 04:25
  • 1
    @erwaman: That might be the Java way, but it's not common in Python. For example, where Java's `Collections.unmodifiableSet` has an `add` method that throws `UnsupportedOperationException`, Python's `frozenset` just doesn't have an `add` method. We don't have rigid `interface`s here, so we don't need a bunch of dummy methods just to match what the interface defines. – user2357112 Jun 28 '16 at 06:12
  • 4
    @user2357112. With `@ABC.abstractmethod` you/we have some rigidness in Python. If class inheriting from parent class `C` won't implement abstract method `M` you will get: `TypeError: Can't instantiate abstract class X with abstract methodsM`. – dzieciou Sep 03 '19 at 02:55
7

According to the Python documentation page, NotImplementedError seems to be an appropriate choice.

user118967
  • 4,895
  • 5
  • 33
  • 54
2

I don't know Java, but looking at what you linked to (and a few examples online), I'd say there is no single equivalent. That is quite a broad description for an exception type.

If the operation isn't supported because the types of the operands are wrong, you'd use TypeError. If it isn't supported because the values are incompatible somehow, you'd use ValueError. Or, as user2357112 notes, you would just do nothing and get an AttributeError when you tried to access a nonexistent method.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384