Why Raise an Exception if Python Raises It Automatically?

exceptionspython

I have a global position keeper of screen items so items don't need store their own positions.

class Screen_Position_Keeper:

    # functions to add stuff

    def get_px_row( self, item ):
        try:
            return self.item_to_row[ item ]
        except KeyError:
            raise KeyError( 'You never registered that item' )

Why not just do the following?

class Screen_Position_Keeper:

    # functions to add stuff

    def get_px_row( self, item ):
        return self.item_to_row[ item ]

Best Answer

The answer to your question is you want meaningful exceptions.

In most contexts, this involves an exception that adds actionable information in one of two ways:

  • Useful typing to the developer who might be catching the exception
  • Useful error information to the user (and/or to the developer who can translate to that the user)

In your example, you aren't really adding anything to the normal exception. Catching and then effectively reraising the exception isn't useful. You could log this information, in which case you now added some value to the exception, but otherwise it's pointless.

Imagine this scenario:

try:
   my_web_function()
except my_custom_web_exception:
   do_something_with_this_exception()

It's entirely reasonable to imagine this scenario. You might make an http request. Most libraries have defined exception types, so you could catch those exceptions, and if it happens, do something.

The "something" is dependent on the specific application. In a http exception, maybe it's just retry the request. Etc.

But the point is catching the exception adds value and information and is actionable.