473,394 Members | 1,944 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

Best practise hierarchy for user-defined exceptions

Hi there,

I am a newcomer to Pyhton coming from Java working on a relatively
large Pyhton project with several packages and modules. To improve
exception handling I would like to introduce some user-defined
exceptions to distinguish between exceptions raised in self-written
code as compared to std libray modules used there-in.

Say, for instance I would like to define a MyParseError exception to
indicate that something has gone wrong while parsing a byte string, a
file, or while packing into or unpacking from a struct.Struct
instance.

Here is my stub-implemented idea on how to do it so far, which is
inspired by how I would have done it in Java (but which may not be
very Pythonic??):

class MyException(Exception):

pass

class MyStandardError(MyException, StandardError):

pass

class MyParseError(MyStandardError, ValueError):

pass

Some comments and questions

1. The hierarchy is deliberately deep and maps to the std library such
that it is easier to extend
2. The implementations are empty but can be extended with hook for
logging, statistics, etc.
3. I use multiple inheritance in the two sub-classes. I have not tried
that before. Is this A Good Thing or A Bad Thing to do?
4. Which __xx__ methods would you normally implement for the user-
defined exception classes? I was thinking of __str__, for example? Is
there a recommended __str__ idiom to use for that?

-- Slaunger
Nov 17 '08 #1
4 3605
On Mon, Nov 17, 2008 at 3:47 AM, Slaunger <Sl******@gmail.comwrote:
Hi there,

I am a newcomer to Pyhton coming from Java working on a relatively
large Pyhton project with several packages and modules. To improve
exception handling I would like to introduce some user-defined
exceptions to distinguish between exceptions raised in self-written
code as compared to std libray modules used there-in.

Say, for instance I would like to define a MyParseError exception to
indicate that something has gone wrong while parsing a byte string, a
file, or while packing into or unpacking from a struct.Struct
instance.

Here is my stub-implemented idea on how to do it so far, which is
inspired by how I would have done it in Java (but which may not be
very Pythonic??):

class MyException(Exception):

pass
The above class probably isn't necessary. You don't need to
overgeneralize this much.
class MyStandardError(MyException, StandardError):

pass
Rename the previous class to just MyError in light of removing the other class.
>
class MyParseError(MyStandardError, ValueError):

pass
This technique is very Pythonic. Subclass from both the exception
class for your module and from a built-in one if there's an applicable
one.
>
Some comments and questions

1. The hierarchy is deliberately deep and maps to the std library such
that it is easier to extend
Zen of Python: Flat is better than nested.
This is part of the reason I recommend removing the one class.
2. The implementations are empty but can be extended with hook for
logging, statistics, etc.
True of stubs in general...
3. I use multiple inheritance in the two sub-classes. I have not tried
that before. Is this A Good Thing or A Bad Thing to do?
Good in this case, just be careful to use super() if you override any methods.
4. Which __xx__ methods would you normally implement for the user-
defined exception classes? I was thinking of __str__, for example? Is
there a recommended __str__ idiom to use for that?
You might override __init__ if you want to store additional
information about the cause of the exception (e.g. location of parse
error, name of the rule the error occurred in, etc).
The __str__ inherited from Exception is usually sufficient, but you
can override it if you want to. it's a judgement call IMHO.

Cheers,
Chris
--
Follow the path of the Iguana...
http://rebertia.com
>
-- Slaunger
--
http://mail.python.org/mailman/listinfo/python-list
Nov 17 '08 #2
On 17 Nov., 13:05, "Chris Rebert" <c...@rebertia.comwrote:
On Mon, Nov 17, 2008 at 3:47 AM, Slaunger <Slaun...@gmail.comwrote:
.....
Here is my stub-implemented idea on how to do it so far, which is
inspired by how I would have done it in Java (but which may not be
very Pythonic??):
class MyException(Exception):
* *pass

The above class probably isn't necessary. You don't need to
overgeneralize this much.
Seems reasonable.
class MyStandardError(MyException, StandardError):
* *pass

Rename the previous class to just MyError in light of removing the other class.

OK.
>
class MyParseError(MyStandardError, ValueError):
* pass

This technique is very Pythonic. Subclass from both the exception
class for your module and from a built-in one if there's an applicable
one.

OK. One thing I *like* about it is that I inherit properties of
ValueError.

One thing I feel *a little uneasy about* is that if I do something
like this

try:
do_something_which_raises_MyParseError_which_I_hav e_overlooked()
do_something_where_I_know_a_ValueError_can_be_rais ed()
catch ValueError:
handle_the_anticipated_ValueError_from_std_lib()
finally:
....

I will not notice that it was an unanticpated condition in my own
code, which caused the ValueError
to be raised. If I had just inherited from MyError, it would fall
through (which I would prefer)

Once I had seen a trace back to the unanticipated MyParseError I would
of course correct the code to

try:
do_something_where_I_now_know_MyParseError_can_be_ raised()
do_something_where_I_know_a_ValueError_can_be_rais ed()
catch MyParseError:
handle_the_anticipated_MyParseError_generated_in_o wn_code()
catch ValueError:
handle_the_anticipated_ValueError_from_std_lib()
finally:
....

Is the above multiple catch methology pythonic as well?

On the other hand, with multiple inheritance this works:

try:
do_something_where_I_know_a_MyParseError_can_be_ra ised()
do_something_where_I_know_a_ValueError_can_be_rais ed()
catch ValueError:
handle_a_MyParseError_or_a_ValueError_in_the_same_ manner()
finally:
....

which is nice is you are very aware that MyParseError descends from
ValueError (which may not be self-evident)

>
Some comments and questions
1. The hierarchy is deliberately deep and maps to the std library such
that it is easier to extend

Zen of Python: Flat is better than nested.
This is part of the reason I recommend removing the one class.
Ah, OK, have to adjust my mindset a little. Willing to accomodate
though... ;-)
>
3. I use multiple inheritance in the two sub-classes. I have not tried
that before. Is this A Good Thing or A Bad Thing to do?

Good in this case, just be careful to use super() if you override any methods.
I will!
>
4. Which __xx__ methods would you normally implement for the user-
defined exception classes? I was thinking of __str__, for example? Is
there a recommended __str__ idiom to use for that?

You might override __init__ if you want to store additional
information about the cause of the exception (e.g. location of parse
error, name of the rule the error occurred in, etc).
The __str__ inherited from Exception is usually sufficient, but you
can override it if you want to. it's a judgement call IMHO.
OK. Seems pretty straight-forward. I like Python more and more.
Cheers,
Chris
That was a very useful answer. Thank you, Chris for taking your time
to reply on my questions.

Cheers,
-- Slaunger
Nov 17 '08 #3
Slaunger <Sl******@gmail.comwrote:
On 17 Nov., 13:05, "Chris Rebert" <c...@rebertia.comwrote:
On Mon, Nov 17, 2008 at 3:47 AM, Slaunger <Slaun...@gmail.comwrote:
.....
Here is my stub-implemented idea on how to do it so far, which is
inspired by how I would have done it in Java (but which may not be
very Pythonic??):
class MyException(Exception):
? ?pass
The above class probably isn't necessary. You don't need to
overgeneralize this much.
Seems reasonable.
class MyStandardError(MyException, StandardError):
? ?pass
Rename the previous class to just MyError in light of removing the other class.
OK.
class MyParseError(MyStandardError, ValueError):
? pass
This technique is very Pythonic. Subclass from both the exception
class for your module and from a built-in one if there's an applicable
one.
OK. One thing I *like* about it is that I inherit properties of
ValueError.

One thing I feel *a little uneasy about* is that if I do something
like this

try:
do_something_which_raises_MyParseError_which_I_hav e_overlooked()
do_something_where_I_know_a_ValueError_can_be_rais ed()
catch ValueError:
handle_the_anticipated_ValueError_from_std_lib()
finally:
....

I will not notice that it was an unanticpated condition in my own
code, which caused the ValueError
to be raised. If I had just inherited from MyError, it would fall
through (which I would prefer)
I'd say if the above code worries you, then MyParseError isn't a
ValueError and you shouldn't inherit from ValueError.

--
Nick Craig-Wood <ni**@craig-wood.com-- http://www.craig-wood.com/nick
Nov 17 '08 #4
Nick Craig-Wood wrote:
Slaunger <Sl******@gmail.comwrote:
>.... I will not notice that it was an unanticpated condition
in my own code, which caused the ValueError to be raised.
If I had just inherited from MyError, it would fall through....

I'd say if the above code worries you, then MyParseError isn't a
ValueError and you shouldn't inherit from ValueError.
Just from the name, I'd look into making MyParseError inherit from
SyntaxError.

--Scott David Daniels
Sc***********@Acm.Org
Nov 19 '08 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
by: Dave Smithz | last post by:
Having adopted someone else's PHP cope and completing a crash course in the language I came across a (probably common) problem with the current code. On a registration form, whenever users names...
2
by: Aadam | last post by:
Does Microsoft have a best practices for tracking errors? (like in a database, what info, etc)
0
by: Daniel Reber | last post by:
I am looking to populate classes (I will have two types of classes, dimensions & facts) in c# with flat data from a summarized dataset. Based on what the user wants I will create a hierarchy of...
0
by: Daniel Reber | last post by:
I am looking to populate classes (I will have two types of classes, dimensions & facts) in c# with flat data from a summarized dataset. Based on what the user wants I will create a hierarchy of...
10
by: Barry Morris | last post by:
Hi I am a php newbie although I have been a programmer for years, this can be dangerous because all the languages I know use = as equal comparison so it took me a long time to debug if ($STRING...
3
by: cbrown | last post by:
I am rebuilding an existing application that relies on an SQL DB. The app is a scheduling/employee management program. My question pertains to best practices in dotnet and database. I use a 3...
4
by: Ned Balzer | last post by:
Hi all, I am pretty new to asp.net; I've done lots of classic asp, but am just beginning to get my mind wrapped around .net. What I'd like to do is include some code that tests if a user is...
2
by: Tomas | last post by:
Hi, I am a VB.NET newbie that would like to know the best practise when working with objects and undo user changes to objects properties. Problem The system allows the user to change...
9
by: Paul | last post by:
Hi, I feel I'm going around circles on this one and would appreciate some other points of view. From a design / encapsulation point of view, what's the best practise for returning a private...
41
by: =?Utf-8?B?VGltIE1hcnNkZW4=?= | last post by:
Hi, I am after suggestions on the best practice declaring and destroying objects. some example code: Private Sub MySub Dim frmMyForm As MyForm Try
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.