473,588 Members | 2,469 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Custom exceptions -- inherit from exceptions.Exce ption?

Is there any particular good reason to inherit from
exceptions.Exce ption? I've never seen any code that depends on what
the base class(es) of a raised exception is (are).

My use case is in a game I am writing. The code for my Game class
contains the following:

class Game (object):

def start (self):
try:
self.players[1]
except IndexError:
raise NotEnoughPlayer s

where NotEnoughPlayer s is really just an empty classic class suitable
for raising. Is there any benefit to importing exceptions and
inheriting from exceptions.Exce ption, other than maybe theoretical
purity?

Thanks!
Jul 18 '05 #1
3 7286
pw*******@adelp hia.net (Paul Miller) writes:
where NotEnoughPlayer s is really just an empty classic class suitable
for raising. Is there any benefit to importing exceptions and
inheriting from exceptions.Exce ption, other than maybe theoretical
purity?


The idea is that, eventually, you can replace

except:

with

except Exception:

with the additional advantage of being able to write

except Exception,e:

Python does not yet enforce exception to inherit from Exception,
but it might some day, at which point you don't have to change
your code.

Regards,
Martin
Jul 18 '05 #2
Paul Miller wrote:
Is there any particular good reason to inherit from
exceptions.Exc eption? I've never seen any code that depends on what
the base class(es) of a raised exception is (are).

I see it all the time:

try:
blah()
except Exception, err: # want to get err object here...
doSomethingToEr r( err ) # e.g. log, or add extra data to the
exception instance
raise

Having all exceptions part of the main tree works very nicely for that
kind of thing.
....
where NotEnoughPlayer s is really just an empty classic class suitable
for raising. Is there any benefit to importing exceptions and
inheriting from exceptions.Exce ption, other than maybe theoretical
purity?

Just as a note, you only have to do this:

class NotEnoughPlayer s( Exception ):
pass

as Exception is in the __builtin__ module.

The "theoretica l purity" comes at a fairly low cost, and gives quite a
bit back IMO. Going even a step further and organising the errors you
raise into a reasonable hierarchy, (preferably using standard exceptions
as base-classes) is often likely to pay dividends as well, but that's
another kettle of Cod.

Enjoy,
Mike

_______________ _______________ _________
Mike C. Fletcher
Designer, VR Plumber, Coder
http://members.rogers.com/mcfletch/


Jul 18 '05 #3
Paul Miller wrote:
Is there any particular good reason to inherit from
exceptions.Exce ption? I've never seen any code that depends on what
the base class(es) of a raised exception is (are).

My use case is in a game I am writing. The code for my Game class
contains the following:

class Game (object):

def start (self):
try:
self.players[1]
except IndexError:
raise NotEnoughPlayer s

where NotEnoughPlayer s is really just an empty classic class suitable
for raising. Is there any benefit to importing exceptions and
inheriting from exceptions.Exce ption, other than maybe theoretical
purity?


Besides the advantage, already pointed out to you, that "except X,x:"
catches all exceptions of any subclass of X (not just of class X itself),
you do get a small but useful amount of "machinery" from class
Exception:
class X(Exception): pass .... try: raise X(23)

.... except Exception, e: print 'error', e
....
error 23

i.e., Exception subclasses may be instantiated with arguments and
their instances display those arguments when printed.
Alex

Jul 18 '05 #4

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

Similar topics

0
1215
by: Ken Varn | last post by:
I want to place my own Unhandled Exception Handler application as part of the DbgManagedDebugger registry entry. It is my understanding that you can substitute your own clr unhandled exception application. Can someone explain the command line arguments that are passed to this application from the clr? I am hoping to get stack trace information so that I can silently log it to
5
6760
by: Dave | last post by:
Hello all, Unfortunately, the reference I have is a bit slim on describing how to create user-defined exceptions derived from std::exception. I think what I have below will work, but is it the way the mechanism was intended to be used? Thanks, Dave
11
1455
by: C# Learner | last post by:
What type of exception should I throw when my code detects that a connection has dropped (i.e. NetworkStream.Read() returns 0)? Should I just throw a SocketException or should I create my own class and throw that instead -- what would be the usual practise in a case like this?
9
1855
by: Jeff Louie | last post by:
I drank too much coffee last night and came up with a suggestion about how to add checked exceptions to C# http://www.geocities.com/jeff_louie/OOP/oop14.htm Comments expected <g> Regards, Jeff
5
390
by: Bevo | last post by:
In my enterprise application I'd like my DataAccess layer to be responsible for handling all database error situations and to basically throw custom exceptions according to whether db connection is ok or not, that is, cDBDownException if ok or cDBException if not ok. These two exceptions would provide all information about the original cause etc. 1. Is this a wise exception handling policy? 2. We use both Oracle and SQL Server. Which...
2
5862
by: Rajeev Soni | last post by:
Hi, Considering the scenario for handling exceptions in Web Application where we have Presentation layer, Business layer and Data Access layer; if there any exception is occurred in DAL, what is the best thing to do: 1. Dont catch the exception in DAL and let it prop up to the Application level and the Global.Application_Error event log it to any source and show let ASP.NET show custom error page provided in Web.Config file. OR 2....
2
937
by: Parag | last post by:
Hi, I am writing error handling mechanism for a large website and one of the requirements that has come is whether it is possible to have the ..NET application whenever it throws exception it throws a custom defined exception. For e.g. Default behaviour is as shown: Try some code Catch Ex as Exception
15
2707
by: bill salkin | last post by:
I'd like to create a custom error handler like this in VB.NET: .... try ... Throw ("Lender Name not in table") .... catch ("Lender Name not in table")
6
1709
by: Lance | last post by:
hi all, using the following code, i never get a message box showing the error, but the default error sound is produced (like there should be an accompanying messagebox). \\\\\\\\\\ Dim FI As FileInfo = _ My.Computer.FileSystem.GetFileInfo(txtSelectedDocument.Text) Try My.Computer.FileSystem.CopyDirectory(FI.DirectoryName, _
0
7929
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
7862
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8228
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
6634
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
5729
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
3847
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
3887
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2372
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
1196
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.