Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Practices for Python Exceptions?

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.

like image 977
UberJumper Avatar asked May 08 '09 12:05

UberJumper


People also ask

How do you deal with exception handling in Python effectively?

To handle exceptions in Python, you first need to wrap your code in a try... except block. Occasionally, you might need to include a finally statement to handle further actions, depending on your needs. As mentioned earlier, you can also use finally in an exception block.

Why is it best practice to have multiple except statements?

Why is it best practice to have multiple except statements with each type of error labeled correctly? Ensure the error is caught so the program will terminate In order to know what type of error was thrown and the.

Is try except a good practice?

What is the reason for the try-except-else to exist? A try block allows you to handle an expected error. The except block should only catch exceptions you are prepared to handle. If you handle an unexpected error, your code may do the wrong thing and hide bugs.


2 Answers

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

like image 130
Eli Bendersky Avatar answered Oct 16 '22 10:10

Eli Bendersky


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"

like image 44
S.Lott Avatar answered Oct 16 '22 08:10

S.Lott