473,320 Members | 2,012 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,320 software developers and data experts.

Exceptions and static constructors.

VS .NET 2003 CF
In this method I cannot catch exceptions thrown by Settings constructor (for
example FileNotFoundException) but only an OutOfMemory exception due to Get
returning void.
Why???

private void GtmForm_Load(object sender, System.EventArgs e)
{
try
{
this.idLength = uint.Parse(Settings.Get("idLength"));
}
catch(FileNotFoundException fnfEx)
{
MessageBox.Show(fnfEx.Message);
Application.Exit();
}
catch(XmlException xmlEx)
{
MessageBox.Show(xmlEx.Message + "\n" +
xmlEx.InnerException.Message);
Application.Exit();
}
catch(Exception ex)
{
MessageBox.Show("Error loading configuration file!\n" + ex.Message);
Application.Exit();
}

this.employeeAssetIdTextBox.Focus();
}

public class Settings
{
private static readonly string path;
private static readonly NameValueCollection appSettings;

static Settings()
{
path =
Path.GetDirectoryName(System.Reflection.Assembly.G etExecutingAssembly().GetName().CodeBase);
path += @"\Setting.xml";

if (!File.Exists(path))
{
throw new FileNotFoundException(path + " could not be found!");
}

appSettings = new NameValueCollection();
try
{
XmlTextReader appSettingsReader = new XmlTextReader(path);

while (appSettingsReader.Read())
{
if (appSettingsReader.NodeType == XmlNodeType.Element &&
appSettingsReader.AttributeCount == 2)
{
appSettings.Add(appSettingsReader.GetAttribute(0),
appSettingsReader.GetAttribute(1));
}
}
}
catch(XmlException e)
{
throw new XmlException("Error processing configuration
file!",e);
}
}

public static string Get(string key)
{
try
{
return appSettings.Get(key);
}
catch(FileNotFoundException)
{
throw new FileNotFoundException(path + " could not be found!");
}
catch(XmlException e)
{
throw new XmlException("Error processing configuration
file!",e);
}
}
}
Apr 17 '07 #1
4 3138
<"BLUE" <blue>wrote:
VS .NET 2003 CF
In this method I cannot catch exceptions thrown by Settings constructor (for
example FileNotFoundException) but only an OutOfMemory exception due to Get
returning void.
Why???
The static constructor will throw a TypeInitializationException with
the actual exception as an inner exception.

However, it's very bad form to do so much work within a static
constructor. For one thing, once a type has failed to load, you won't
be able to use it within that AppDomain, even if you "fix" whatever was
wrong.

You'd be better off setting appSettings within a "getter" property
using a lock for thread-safety. That way you don't need to worry about
any wrappers etc, you'll just get the normal exception.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Apr 17 '07 #2
The static constructor will throw a TypeInitializationException

try
{
this.idLength = uint.Parse(Settings.Get("idLength"));
}
catch(Exception ex)
{
MessageBox.Show("Error loading configuration file!\n" + ex.Message);
Application.Exit();
}

Debugging this code the Exception type is OutOfMemory not
TypeInitializationException.
File loading or DB connections could be done (with exception management and
MessageBox showing errors) in form load event?
Or it would be better to do them while handling another event?

You'd be better off setting appSettings within a "getter" property using a
lock for thread-safety
Using a getter property that returns appSettings I have no more
encapsulation: I receive a collection instead of a string.
Using a getter property that returns a value I have no more indipendence
from the key name.
Using my Get method means loading the file each time I request a setting.
That's why I've done so.
Thanks,
Luigi.
Apr 17 '07 #3
<"BLUE" <blue>wrote:
The static constructor will throw a TypeInitializationException

try
{
this.idLength = uint.Parse(Settings.Get("idLength"));
}
catch(Exception ex)
{
MessageBox.Show("Error loading configuration file!\n" + ex.Message);
Application.Exit();
}

Debugging this code the Exception type is OutOfMemory not
TypeInitializationException.
That's very strange - certainly on my box, I get a
TypeInitializationException.
File loading or DB connections could be done (with exception management and
MessageBox showing errors) in form load event?
Or it would be better to do them while handling another event?
I'd personally do it before even loading any forms, in the main method,
if the files not existing (or whatever) will basically mean that your
app can't start.
You'd be better off setting appSettings within a "getter" property using a
lock for thread-safety

Using a getter property that returns appSettings I have no more
encapsulation: I receive a collection instead of a string.
No, you'd call the getter within Settings.Get and any other Settings
methods. It would be a private property. Sorry for not making that
clearer.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Apr 17 '07 #4
No, you'd call the getter within Settings.Get and any other Settings
methods. It would be a private property. Sorry for not making that
clearer.
Than you very much!
Now it works!!!
Apr 18 '07 #5

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

Similar topics

5
by: John | last post by:
Hi, In my years as a VB programmer, I have settled into this pattern of creating collections classes, with an AddNew() method. AddNew() validates the parameters, instantiates the object, adds...
8
by: Shane Groff | last post by:
I know this is a recurring discussion (I've spent the last 3 days reading through threads on the topic), but I feel compelled to start it up again. After reading through the existing threads, I...
10
by: Brian Folke Seaberg | last post by:
I was recently browsing a couple of C++ books at the local bookstore. One book called throwing exceptions from constructors a "dubious practice." Another book recommended not throwing...
21
by: mihai | last post by:
People say that is a bad technique to throw exception from constructors; and that the solution would be to create a function _create_ to initialize an object. What about copy constructors? How...
9
by: A J Le Couteur Bisson | last post by:
Could someone please confirm that static class constructors are only called at the first use of a non-static constructor on the class, or am I doing something wrong? If this is indeed the case...
4
by: KC | last post by:
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...
5
by: tryptik | last post by:
All- I have heard differing points of view on whether or not constructors should throw. I am working on a library, and I need to know if it is bad form for a consturctor to throw. Thanks -J
24
by: usenet | last post by:
I am unable to catch floating exceptions (e.g. divide by 0 or 0/0) using the standard exceptions defined in stdexcept. What is the recommended way to catch such exceptions? Thanks, Song
0
RedSon
by: RedSon | last post by:
Chapter 3: What are the most common Exceptions and what do they mean? As we saw in the last chapter, there isn't only the standard Exception, but you also get special exceptions like...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
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...

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.