77

What are the best practices for creating exceptions? I just saw this, and I don't know if I should be horrified, or like it. I read several times in books that exceptions should never ever hold a string, because strings themselves can throw exceptions. Any real truth to this?

Basically from my understanding from the scripts is that this was done so all the inhouse Python libraries will have a common error message format (something that is desperately needed) so I can understand why putting the error message string is a good idea. (Almost every method throws exceptions due to the utter need for nothing invalid getting through).

The code in question is the following:

"""
Base Exception, Error
"""
class Error(Exception):
    def __init__(self, message):
        self.message = message

    def __str__(self):
        return "[ERROR] %s\n" % str(self.message)

    def log(self):
        ret = "%s" % str(self.message)
        if(hasattr(self, "reason")):
            return "".join([ret, "\n==> %s" % str(self.reason)])
        return ret

class PCSException(Error):
    def __init__(self, message, reason = None):
        self.message = message
        self.reason = reason
    def __str__(self):
        ret = "[PCS_ERROR] %s\n" % str(self.message)
        if(self.reason != None):
            ret += "[REASON] %s\n" % str(self.reason)
        return ret

This is just the tip of the iceberg, but can someone give me some insight in what makes this a terrible idea? Or if there is a much better exception coding process/style.

JS.
  • 14,781
  • 13
  • 63
  • 75
UberJumper
  • 20,245
  • 19
  • 69
  • 87
  • I think the best way is to have as deep a hierarchy of exceptions as possible, to give maximum information to the programmer. I recommend something like this for example (from bottom up): WrongInputError -> InputError -> GeneralInputError -> NonCriticalError -> Error -> GeneralError -> BaseError -> WhyIsThisHappeningerror. – Andriy Drozdyuk May 08 '09 at 13:34

5 Answers5

94

Robust exception handling (in Python) - a "best practices for Python exceptions" blog post I wrote a while ago. You may find it useful.

Some key points from the blog:

Never use exceptions for flow-control

Exceptions exist for exceptional situations: events that are not a part of normal execution.

Consider 'find' on a string returning -1 if the pattern isn't found, but indexing beyond the end of a string raises an exception. Not finding the string is normal execution.

Handle exceptions at the level that knows how to handle them

...

The best place is that piece of code that can handle the exception. For some exceptions, like programming errors (e.g. IndexError, TypeError, NameError etc.) exceptions are best left to the programmer / user, because "handling" them will just hide real bugs.

Always ask "is this the right place to handle this exception?" and be careful with catching all exceptions.

Document the exceptions thrown by your code

...

thinking about which exceptions your code may throw will help you write better, safer and more encapsulated code

D. A.
  • 3,369
  • 3
  • 31
  • 34
Eli Bendersky
  • 263,248
  • 89
  • 350
  • 412
  • 4
    It's customary to provide a synopsis of external links. – dbn Jun 13 '14 at 23:20
  • 4
    I'm not sure I remember what was customary in 2009 when this answer was posted :-) Feel free to suggest an edit – Eli Bendersky Jun 14 '14 at 00:42
  • 2
    Nevertheless, his article is well worth reading in its entirety and makes valuable contribution in answering this question. – Russ Bateman Mar 27 '15 at 14:28
  • 10
    Isn't it pretty much standard encouraged practice to use exceptions for flow control? That's sort of the point of the `try/catch/else` pattern, no? For loops in Python use an exception to know when to stop an iterator in a for loop. It is literally impossible to do basic program control without implicitly using exceptions. – eric Dec 12 '17 at 05:53
  • I don't think it's true that it's "impossible" to do flow control without exceptions. Some language use continuations, some language use value-based error propagations. Python's `if/elif/else`, `or`, `and` and other shortcircuiting/flow control operators and statements don't use exceptions as far as I know. But yes, exceptions can and are used for flow control in Python. It might be a bad practice to do so without abstracting over the mechanics(like is done for the iterator protocol by using `next` method and `for` statement), though. – Charles Langlois Dec 21 '17 at 18:31
37

I read several times in books that exceptions should never ever hold a string, because strings themselves can throw exceptions. Any real truth to this?

What?

Please provide a reference or a link to this. It's totally untrue.

Since all objects can throw exceptions, no object could be contained in an exception by that logic.

No, the "no strings" is simply crazy in a Python context. Perhaps you read it in a C++ context.


Edit

Once upon a time (back in the olden days) you could raise a Python exception by name instead of by the actual class.

raise "SomeNameOfAnExceptionClass"

This is bad. But this is not including a string inside an exception. This is naming the exception with a string instead of the actual class object. In 2.5, this can still work, but gets a deprecation warning.

Perhaps this is what you read "Do not raise an exception with a string name"

Andrew T
  • 5,549
  • 7
  • 43
  • 55
S.Lott
  • 384,516
  • 81
  • 508
  • 779
  • Your right now that i think about it. Most of them were C++ books, but i clearly remeber reading a python book, where it said in big bold letters "exceptions should never hold the error message, they should just hold a small identifier (number or maybe a small string)" i don't remeber the book, but i'll see if i can dig it up. – UberJumper May 08 '09 at 13:01
  • 8
    Maybe it was referring to the fact that you should not use an Exception class for multiple exceptional situations. Like MyFrameworkException('File not found') and MyFrameworkException('Database connection unavailable'). – Ionuț G. Stan May 08 '09 at 13:04
  • +1 Having strings in exceptions is very useful. Other languages besides Python also support adding descriptive info to the error constructs or exceptions... they may call it a "context" or a "reason", and may represent it as a string or some other object, but it's still the same deal. – Jarret Hardie May 08 '09 at 13:08
  • I always put some message useful for the developer into the exception - they, and the log output, are for development purposes as far as I'm concerned. Possibly the book you read was by someone who likes to handle user-facing errors using exceptions. – millimoose May 08 '09 at 13:23
  • 2
    Err, I don't think you're correct about how raise used to work. raise used to accept strings because that string *would be the exception*. It wouldn't take the string and instantiate some other object, it would literally throw the string. Or so I thought. Thus why there's python code like: raise "Here is my nice verbose error message" – Joseph Garvin May 26 '09 at 18:18
  • +1 I'm glad there are old farts around that remember this stuff! – Matt Joiner Mar 25 '11 at 11:07
11

I believe the advice against creating exceptions with a string comes from "Learning Python" (O'Reilly). In a section entitled String Exceptions Are Right Out!, it points out the (now removed) ability to create an exception directly with an arbitrary string.

The code it gives as an example is:

myexc = "My exception string"
try:
    raise myexc
except myexc:
    print ('caught')

This is on p858 of the Fourth Edition (paperback).

Graham Borland
  • 60,055
  • 21
  • 138
  • 179
4

First impression is that it's entirely too much code for an exception.

Formatting exceptions should be done in logger configuration. Same goes for the logging itself.

It also redefines the standard (and deprecated) message attribute, and doesn't call the superclass constructor. (This might or might not break Python 3.0 exception chaining, I haven't tried because I'm running 2.6)

Most of what the extra code does can be realised using BaseException.args, by logging the following as the "message":

'\n==> '.join(exception.args)

I'd argue that if something can be done using a common / idiomatic mechanism, it should especially be done so in exception handling. (Exceptions being a mechanism to signal something across application layers.)

Personally, I try to avoid anything beyond

class SomeException(Exception): pass

(Disclaimer: answer subjective, possibly by nature of the question.)

millimoose
  • 39,073
  • 9
  • 82
  • 134
  • The main problem with a logger is that some of the scripts are like 20-30 lines. All output is piped to the console by default (and has to be done) – UberJumper May 08 '09 at 14:13
  • You could likely externalise logging configuration into a shared module just like you seem to externalise formatting and logging errors into their definitions. Separation of concerns usually tends to clash with absolute code size though. – millimoose May 08 '09 at 20:22
  • I use nothing beyond the simple class as you mentioned.Would you please help me out on this **_Formatting exceptions should be done in logger configuration._** with a simple and easy to understand example.Thanks – Tara Prasad Gurung Apr 06 '17 at 04:58
0
class Error(Exception):
    """Base class for other exceptions"""
    pass

class empty_string_error(Error):
    """Raised when the input value is too large"""
    pass
while(1):
    try:
        if("Your Condition"):
            raise empty_string_error
        else:
            print("OUTPUT")
    except empty_string_error:
        print("APT MESSAGE")
        print(" ")
    finally:
        pint("Mandatory code")