473,320 Members | 2,080 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.

Throwing exceptions problem

Hi

I understand that a throw statement throws an exception immediately and
unconditionally. Control never reaches the statement immediately following
the throw. The following method seems to stop the statements (if
Enum.IsDefined is false) after the throw and return null to the calling
proceedure. Then the calling proc raises a NullReferenceException. Basically
it looks to me like the throw statement is not stopping the programme
immediately. Can this be true or have I missed something?
public int AddAccount(...byte accountType...)
{
// Check that a valid account type exists as an AccountType Enum
if (!Enum.IsDefined(typeof(AccountTypes), accountType))
throw new ArgumentOutOfRangeException("AccountType must have a matching
Enum.");

....
// do some db inserting
// Add the new account
return account.AccountID;
}

Many thanks
Andrew
Aug 10 '06 #1
10 2488
"J055" <j0**@newsgroups.nospamwrote:
I understand that a throw statement throws an exception immediately and
unconditionally. Control never reaches the statement immediately following
the throw.
Yes.
The following method seems to stop the statements (if
Enum.IsDefined is false) after the throw and return null
That is not possible, since the method returns an 'int' value, which
cannot be null.
to the calling
proceedure. Then the calling proc raises a NullReferenceException. Basically
it looks to me like the throw statement is not stopping the programme
immediately. Can this be true or have I missed something?
public int AddAccount(...byte accountType...)
{
The code looks like it should either throw an exception or return the
value of account.AccountID - if you're getting a NullReferenceException
it might be because 'account' is null. It's not possible to tell much
more without more information or more complete code.

-- Barry

--
http://barrkel.blogspot.com/
Aug 10 '06 #2
Hi Barry

This is the complete method. My Enums don't contain a 0 value so if I send
in an accountType of 0 my ArgumentOutOfRangeException should be raised. I
know that if I remove the throw statements from the method then it always
return an integer. So I don't understand why it should return null if the
ArgumentOutOfRangeException is raised.

Thanks
Andrew

public int AddAccount(string code,

string email,

string password,

string friendlyName,

string firstName,

string lastName,

byte accountType,

bool isActive,

byte role

)

{

// Check that a valid account type exists as an AccountType Enum

if (!Enum.IsDefined(typeof(AccountTypes), accountType))

throw new ArgumentOutOfRangeException("AccountType must have a matching
Enum.");

// Check that a valid role exists in the AccountRoles Enum

if (!Enum.IsDefined(typeof(AccountRoles), role))

throw new ArgumentOutOfRangeException("Role must have a matching
AccountRoles Enum.");
// Create a new AccountsRow instance

ScsDataSet.AccountsDataTable accounts = new ScsDataSet.AccountsDataTable();

ScsDataSet.AccountsRow account = accounts.NewAccountsRow();

account.Code = code;

account.Email = email;

account.Password = password;

account.FriendlyName = friendlyName;

account.FirstName = firstName;

account.LastName = lastName;

account.AccountType = accountType;

account.IsActive = isActive;

account.Role = role;

// Add the new account

accounts.AddAccountsRow(account);

int rowsAffected = Adapter.Update(accounts);
return account.AccountID;

}
Aug 10 '06 #3
Hi again

Don't know if this helps. The ObjectDataSource.InsertMethod is set to the
AddAccount method. I then have the Inserted event handle the returned
integer. This is where I get a NullReferenceException becuase the
e.ReturnValue is a null object. Why does the application not stop at my
thrown exception? It seems to get lost, i.e. no stack trace information or
innerexception seems to be available.

protected void odsAccount_Inserted(object sender,
ObjectDataSourceStatusEventArgs e)
{
Trace.Warn(e.Exception.Message);
// writes out: Exception has been thrown by the target of an invocation.

// add the new AccountID to the Select Parameters
odsAccount.SelectParameters.Add("AccountID", TypeCode.Int32,
e.ReturnValue.ToString());
}
Aug 10 '06 #4
"J055" <j0**@newsgroups.nospamwrote:
This is the complete method. My Enums don't contain a 0 value so if I send
in an accountType of 0 my ArgumentOutOfRangeException should be raised. I
know that if I remove the throw statements from the method then it always
return an integer. So I don't understand why it should return null if the
ArgumentOutOfRangeException is raised.
It *cannot* return a null, because you cannot convert a null value into
a plain integer type ('int'). Put a breakpoint in the code that calls
the method where it receives the return value - or better yet, tell us
where exactly the exception is caused (i.e. enable 'break on exception'
for the appropriate exception if it isn't already, in Debug | Exceptions
menu).

-- Barry

--
http://barrkel.blogspot.com/
Aug 10 '06 #5
J055 <j0**@newsgroups.nospamwrote:
This is the complete method. My Enums don't contain a 0 value so if I send
in an accountType of 0 my ArgumentOutOfRangeException should be raised. I
know that if I remove the throw statements from the method then it always
return an integer. So I don't understand why it should return null if the
ArgumentOutOfRangeException is raised.
Rather than give a complete method, please give a short but complete
program.

See http://www.pobox.com/~skeet/csharp/complete.html for more on what I
mean by that.

--
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
Aug 10 '06 #6
Hi J055,

Since you provided 2 separate code snippets of your project, it is hard for
the community to image the relationship between them, so it is almost
impossible for us to judge if your second reply has anything to do with
first AddAccount() method issue.

Let's focus on your first AddAccount() exception issue first.

To find out why the AddAccount() will return a null reference to the
calling procedure, the simplest way is placing a breakpoint in the
AddAccount() method and run your code under debugger. Then you can use F10
to step through each statement in this method, it should be easy to find
out which statement finally caused the method to exit and why null
reference is returned.

Based on my experience, I suspect the ArgumentOutOfRangeException is not
thrown. Because if the ArgumentOutOfRangeException is thrown, the
AddAccount() method will terminate execution immediately and it will not
return anything to the calling procedure.

Thanks.

Best regards,
Jeffrey Tan
Microsoft Online Community Support
==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.
==================================================
This posting is provided "AS IS" with no warranties, and confers no rights.

Aug 11 '06 #7
Hi Andrew,

I understand that this post is related to your another post "Change
FormView.ChangeMode to Edit after Insert" in
microsoft.public.dotnet.framework.aspnet.

If the insert method of ObjectDataSource throws exception, it will be
catched and stored in the Inserted event's parameter
ObjectDataSourceStatusEventArgs.Exception property:

#ObjectDataSourceStatusEventArgs.Exception Property
http://msdn2.microsoft.com/en-us/lib...rols.objectdat
asourcestatuseventargs.exception.aspx

You need to check for the Exception property before reading the ReturnValue:

protected void odsAccount_Inserted(object sender,
ObjectDataSourceStatusEventArgs e)
{
if (e.Exception != null) {
Trace.Warn(e.Exception.Message);
// writes out: Exception has been thrown by the target of an
invocation.
} else {
// add the new AccountID to the Select Parameters
odsAccount.SelectParameters.Add("AccountID", TypeCode.Int32,
e.ReturnValue.ToString());
}
}

Hope this helps. Please feel free to post here if anything is unclear.

By the way, you don't have to open a new post for this. Since it's related
to your another post, posting there will make others to understand your
question more easier.

Regards,
Walter Wang (wa****@online.microsoft.com, remove 'online.')
Microsoft Online Community Support

==================================================
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
==================================================

This posting is provided "AS IS" with no warranties, and confers no rights.

Aug 11 '06 #8
I forgot to mention that you need to use e.Exception.InnerException to find
the real exception that thrown in the insert method. So you actually want
to log the message using:

Trace.Warn(e.Exception.InnerException.Message);
Regards,
Walter Wang (wa****@online.microsoft.com, remove 'online.')
Microsoft Online Community Support

==================================================
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
==================================================

This posting is provided "AS IS" with no warranties, and confers no rights.

Aug 11 '06 #9
Hi

Thanks for all the advise. Apologies for the confusing posts. I think I have
a clearer picture of what's been happing so I'll try to outline it here:

I'm using ObjectDataSource Insert to call my AddAccount business object. I
want to check some values and throw an exception if they are not expected.
Basically I wasn't seeing the exception because I wasn't handling it in the
web application (Is that what I mean?). I modified the ObjectDataSource
Inserted method as Walter suggested. Now I can see the error.

protected void odsAccount_Inserted(object sender,
ObjectDataSourceStatusEventArgs e)
{
if (e.Exception != null)
{
Trace.Warn(e.Exception.InnerException.Message);
// displays: System.ArgumentOutOfRangeException
}
else
{
// add the new AccountID to the Select Parameters
int accountID = (int)e.ReturnValue;
odsAccount.SelectParameters.Add("AccountID", TypeCode.Int32,
accountID.ToString());
}
}

I need to brush up on handling exceptions, bubbling etc. As I don't expect
to receive the ArgumentOutOfRangeException exception in my working
application (I will use validation controls) should I throw the exception
again in the odsAccount_Inserted method?

Many thanks
Andrew
Aug 11 '06 #10
Hi Andrew,

I think it should be ok to throw e.Exception.InnerException in the Inserted
event. However, depends on your application's actual implementation on
exception handling, you need to test if it works correctly. Pleaes feel
free to post your result here.
Regards,
Walter Wang (wa****@online.microsoft.com, remove 'online.')
Microsoft Online Community Support

==================================================
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
==================================================

This posting is provided "AS IS" with no warranties, and confers no rights.

Aug 13 '06 #11

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

Similar topics

5
by: Mark Oueis | last post by:
I've been struggling with this question for a while. What is better design? To design functions to return error codes when an error occures, or to have them throw exceptions. If you chose the...
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...
1
by: Farooq Khan | last post by:
i'm writing a class library having following code snippet. i want this class to report an error (by throwing an Exception) to the application using this class library. the problem is that within...
40
by: Kevin Yu | last post by:
is it a bad programming design to throw exception in the try block then catch it??
5
by: KJ | last post by:
This is kind of hard to explain but I have a The controls are created with CreateChildControls(). Now let say I click a button and an error occurs in the control. If I throw it up it goes back...
40
by: Sek | last post by:
Is it appropriate to throw exception from a constructor? Thats the only way i could think of to denote the failure of constructor, wherein i am invoking couple of other classes to initialise the...
6
by: Marvin Barley | last post by:
I have a class that throws exceptions in new initializer, and a static array of objects of this type. When something is wrong in initialization, CGI program crashes miserably. Debugging shows...
1
by: usenet | last post by:
I wrote some sample code (see below) for nested exception throwing i.e. my catch blocks are throwing exceptions of their own (for simplicity I used standard exceptions). I am getting some...
4
by: Jay Dee | last post by:
I have a query about throwing exceptions. To throw an exception I type something like: try { // do somthing } catch (ArgumentOutOfRangeException) {
21
by: Chris M. Thomasson | last post by:
Is it every appropriate to throw in a dtor? I am thinking about a simple example of a wrapper around a POSIX file... ________________________________________________________________________ class...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
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: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
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: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
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.