473,385 Members | 1,317 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,385 software developers and data experts.

Singleton designs and exceptions

KC
Greeting all!

I have a problem that I'm hoping will be of interest to others here, and
maybe a solution will crop up. I appoligize for the message's length.

Now, I'm new to C# and .NET, so I am developing an application during my
learning phase. Because of this, I'm trying to use as many *features* as is
reasonable. Some may be more reasonable than others :) Keep that in mind.

OK, basicaly my problem is how to handle exceptions in constructors for
Singletons. Let me set it up:

I have (among others of course) a MainForm class, a Profiles class and a
ProfilesXmlFile class. The purpose of the MainForm class is obvious, the
Profiles class keeps a list of Profile class instances and the
ProfilesXmlFile class reads and writes the list of Profile instances to
an...erm..XML file. A Profile is simply a set of parameters under which the
application works. The user can only select one Profile at any time.

So, I only want/need one instance of the Profiles class, and only one
instance of the ProfilesXmlFile. I can choose many different ways to
approach this, of course, but for the sake of the learning experience I
chose Singletons. I follow MS's recommended approach:

sealed class Profiles {
private ArrayList theProfiles;
public static readonly Profiles Instance = new Profiles();
private Profiles() {
ProfilesXmlFile xmlFile = ProfilesXmlFile.Instance;
theProfiles = xmlFile.LoadProfiles();
}
}

sealed class ProfilesXmlFile {
private XmlDocument doc;
public static readonly ProfilesXmlFile Instance = new ProfilesXmlFile();
private ProfilesXmlFile() {
doc = new XmlDocument();
doc.Load("profiles.xml");
}
public ArrayList LoadProfile() {...}
}

During application initialization, I do this in MainForm:
Profiles myProfiles = Profiles.Instance;

Like I said before, Singletons are not necessary, but it helps me explore
the language.

The problem lies in the exception handling. "doc.Load("profiles.xml")" in
the ProfilesXmlFile class's contructor can throw a couple of exceptions
(FileNotFoundException and XmlException). I want to let the user know that
there was a problem with loading his saved profiles, but ProfilesXmlFile is
not the right place to do that (it is a helper class and should not display
dialog boxes, IMO). Therefore I want to catch the exception and rethrow it
so that Profiles handles it (or prolly even rethrow it there to let MainForm
handle it).

The behaviour is strange though. If I catch FileNotFoundException and
rethrow it (or a custom exception), then I get an "Unhandled exception
FileNotFoundException" raised in that same constructor! The calling class
gets a "TypeInitializationException" (or something like that). I tried for
hours to get some sort of notification to the calling classes that something
went wrong, but the only way to avoid getting "unhandled exception xxx" was
to catch and ignore the exception in the constructor.

How DO you handle exceptions in constructors, and especially for singletons
like the ones I descripbed?

I realize that there are a number of redesigns that will solve the problem.
For instance, I can empty the constructor and do all the work in
LoadProfiles(), which can throw the exceptions. Or I could continue to catch
and set a success/failure flag, and have the calling class do a check to see
if init was successfull. As the class is today, the constructor ignores all
exceptions, but LoadPofiles() checks the status of the doc object (!= null,
HasChildren, etc.).

Anyway, I am probably way out there in la-la land, but let's see what you
think :)
Nov 16 '05 #1
4 2363
KC <no@mail.com> wrote:

<snip>
How DO you handle exceptions in constructors, and especially for singletons
like the ones I descripbed?


What you could do is change Instance to a property like this:

sealed class Profiles
{
static Profiles instance;
static object padlock;

...Constructor as before...

public static Profiles Instance
{
// Thread-safety...
lock (padlock)
{
if (instance==null)
{
// Exception may get thrown here
instance = new Profiles();
}
return instance;
}
}
}

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #2
KC
Thanks for the response.

I see how that could solve it, but that code is not utilizing C#'s built-in
singleton functionality. In that code I have the overhead of locking on
each invokation. That can be fixed with double-checks, i.e.:
if (instance==null)
{
lock (padlock)
{
if (instance==null)
{
// Exception may get thrown here
instance = new Profiles();
}
return instance;
}
}

So, maybe the question should be rephased:
How DO you handle exceptions in constructors, and especially for singletons
like the ones I described, without breaking the MS recommended design (that
uses the built-in functionality).

Thanks again!
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
KC <no@mail.com> wrote:

What you could do is change Instance to a property like this:

sealed class Profiles
{
static Profiles instance;
static object padlock;

...Constructor as before...

public static Profiles Instance
{
// Thread-safety...
lock (padlock)
{
if (instance==null)
{
// Exception may get thrown here
instance = new Profiles();
}
return instance;
}
}
}

Nov 16 '05 #3
KC <no@mail.com> wrote:
Thanks for the response.

I see how that could solve it, but that code is not utilizing C#'s built-in
singleton functionality. In that code I have the overhead of locking on
each invokation. That can be fixed with double-checks, i.e.:
if (instance==null)
{
lock (padlock)
{
if (instance==null)
{
// Exception may get thrown here
instance = new Profiles();
}
return instance;
}
}
No, that *can't* be solved with double-checks, unless instance is
volatile.

See http://www.pobox.com/~skeet/csharp/singleton.html
So, maybe the question should be rephased:
How DO you handle exceptions in constructors, and especially for singletons
like the ones I described, without breaking the MS recommended design (that
uses the built-in functionality).


You could use a static constructor and stash not just the instance but
the exception as well, and make the property:

public Profiles Instance
{
get
{
if (constructionException != null)
{
throw constructionException;
}
return instance;
}
}

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #4
KC
Thanks again!

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message >

No, that *can't* be solved with double-checks, unless instance is
volatile.

See http://www.pobox.com/~skeet/csharp/singleton.html
Well, apparently there is some controversy as to whether that is safe or not
:) Let's leave it
at that. No use risking it though, which is why I like the MS design.
So, maybe the question should be rephased:
How DO you handle exceptions in constructors, and especially for singletons like the ones I described, without breaking the MS recommended design (that uses the built-in functionality).


You could use a static constructor and stash not just the instance but
the exception as well, and make the property:

public Profiles Instance
{
get
{
if (constructionException != null)
{
throw constructionException;
}
return instance;
}
}


Yeah, I like that. So, I make the instance variable private and force the
use of the property, which throws the exception (if there was one). I will
test that tonight :)

Thanks!!!

/Kris
Nov 16 '05 #5

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

Similar topics

7
by: Tim Clacy | last post by:
Is there such a thing as a Singleton template that actually saves programming effort? Is it possible to actually use a template to make an arbitrary class a singleton without having to: a)...
18
by: Alfonso Morra | last post by:
Hi, Anyone knows of a link to a singleton design pattern example in C++ (preferably not using a global variable?).
11
by: Daniel Billingsley | last post by:
Let's say I'm writing a business app and I want there to be only one instance of the Customer object for each particular customer (representing a database record) being edited. Would it be...
21
by: Sharon | last post by:
I wish to build a framework for our developers that will include a singleton pattern. But it can not be a base class because it has a private constructor and therefore can be inherit. I thought...
16
by: ed_p | last post by:
Hello, I have implemented the singleton pattern for a class to hold a SqlConnection object that will be used thruout the application to create commands. My application is a simple Windows Form...
11
by: Eric | last post by:
I have a VB.net dll project with a class that is a singleton. I've been using this in winform apps without any problems. I would like to use this same dll in a web form project but my singleton...
7
by: ThunderMusic | last post by:
Hi, I have a problem regarding singletons in C#. What I would like to do is the following ClassA is a singleton ClassB inherits from ClassA and is also a Singleton there cannot and instance of...
3
by: dischdennis | last post by:
Hello List, I would like to make a singleton class in python 2.4.3, I found this pattern in the web: class Singleton: __single = None def __init__( self ): if Singleton.__single: raise...
3
by: stevewilliams2004 | last post by:
I am attempting to create a singleton, and was wondering if someone could give me a sanity check on the design - does it accomplish my constraints, and/or am I over complicating things. My design...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
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: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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...

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.