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

Is There a Way to Avoid This Mess?

Is there a way to avoid the following mess?

int i = 0;
if (someString != null) {
try {
i = Int32.Parse(someString);
} catch (FormatException) {

}
}

More specifically, is there a way of avoiding the ugly empty catch
statement?
Nov 15 '05 #1
17 1530
Yes, put the mess in a function somewhere.

public int ToInt32(object value)
{
try
{
return Convert.ToInt32(value);
}
catch { }
}

"C# Learner" <cs****@learner.here> wrote in message
news:uT**************@TK2MSFTNGP10.phx.gbl...
Is there a way to avoid the following mess?

int i = 0;
if (someString != null) {
try {
i = Int32.Parse(someString);
} catch (FormatException) {

}
}

More specifically, is there a way of avoiding the ugly empty catch
statement?

Nov 15 '05 #2
Michael Culley wrote:
Yes, put the mess in a function somewhere.

public int ToInt32(object value)
{
try
{
return Convert.ToInt32(value);
}
catch { }
}


Isn't that a nasty "hack" though? Surely there's a better way?!
Nov 15 '05 #3
Not Really,
It is no different than if you tried to use Integer.ParseInt(string) in
java.

I dont remember off hand how it is done in c++ but it might be similar.
I know there is no implicit conversion so it is probably sitting in string.h
somewhere ctoi probably

Dave

"C# Learner" <cs****@learner.here> wrote in message
news:ea**************@TK2MSFTNGP11.phx.gbl...
Michael Culley wrote:
Yes, put the mess in a function somewhere.

public int ToInt32(object value)
{
try
{
return Convert.ToInt32(value);
}
catch { }
}


Isn't that a nasty "hack" though? Surely there's a better way?!

Nov 15 '05 #4

If you are gone do anything with the exception, then just don't catch it, I mean..
public int ToInt32(object value

return Convert.ToInt32(value)
Nov 15 '05 #5
Hector Martinez wrote:

If you are gone do anything with the exception, then just don't catch it, I mean...
public int ToInt32(object value)
{
return Convert.ToInt32(value);
}


But I *need* to catch the exception, or else it'll bubble up and
eventually cause an exception dialog to show.
Nov 15 '05 #6
Dave Quigley wrote:
Not Really,
It is no different than if you tried to use Integer.ParseInt(string) in
java.

I dont remember off hand how it is done in c++ but it might be similar.
I know there is no implicit conversion so it is probably sitting in string.h
somewhere ctoi probably
It's atoi() in ANSI C. On success, it returns the converted integer.
On failure, it returns 0. This would be ideal here!
Dave

Nov 15 '05 #7
C# Learner wrote:

<snip>

Well, I guess I'll have to write my own (efficient one) that returns a
default value passed to it on error.

..NET let me down *again*.

Thanks for the replies.
Nov 15 '05 #8

Yeah, but that's not what you want now is it? At least not in most cases. 0
is a valid value that an int can hold. This is hardly a solution.
+++ Rick ---

--

Rick Strahl
West Wind Technologies
http://www.west-wind.com/
http://www.west-wind.com/weblog/
----------------------------------
Making waves on the Web
"C# Learner" <cs****@learner.here> wrote in message
news:eH**************@TK2MSFTNGP10.phx.gbl...
Dave Quigley wrote:
Not Really,
It is no different than if you tried to use Integer.ParseInt(string) in java.

I dont remember off hand how it is done in c++ but it might be similar. I know there is no implicit conversion so it is probably sitting in string.h somewhere ctoi probably


It's atoi() in ANSI C. On success, it returns the converted integer.
On failure, it returns 0. This would be ideal here!
Dave

Nov 15 '05 #9
Rick Strahl [MVP] wrote:
Yeah, but that's not what you want now is it? At least not in most cases. 0
is a valid value that an int can hold. This is hardly a solution.

+++ Rick ---


It would be ideal _here_, but I can definitely see your point with
regards to /general/ usage.

Better would be something like:

int n = ToInt32Def(someString, 0); // 0 is the value to return on error

or perhaps:

bool succeded = TryToInt32(somestring, out n);
Nov 15 '05 #10
it's a not a good idea to write your OWN one,

and it'll not be a efficient one,

and anyway you should process the exception.

so write a warpper

public int ToInt32(object value){...}

is THE soluton.


Nov 15 '05 #11
You need TryParse -- it attempts the parse, and returns true/false on
success/failure. Problem is that it *only* is available for the double type --
don't ask me why, more .NET shortsightedness...

So, you could do the following:

double result = 0;
int i = double.TryParse(someString, style*, provider*, result) ? (int)result :
0;

A *little* cleaner.

*Define style and provider to your specific needs

C# Learner wrote:

Is there a way to avoid the following mess?

int i = 0;
if (someString != null) {
try {
i = Int32.Parse(someString);
} catch (FormatException) {

}
}

More specifically, is there a way of avoiding the ugly empty catch
statement?

Nov 15 '05 #12
C# Learner <cs****@learner.here> wrote:
C# Learner wrote:

<snip>

Well, I guess I'll have to write my own (efficient one) that returns a
default value passed to it on error.

.NET let me down *again*.


I don't see why this is such a let down for you. Yes, you have to write
a method which is all of about 8 lines long. Why is that such a
problem? You shouldn't expect .NET to provide you absolutely everything
gift-wrapped: you should expect it to provide you enough tools so that
you can reasonably easily get the effect you want, just as you can
here.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #13
Jon Skeet [C# MVP] wrote:
C# Learner <cs****@learner.here> wrote:


<snip>
.NET let me down *again*.


I don't see why this is such a let down for you. Yes, you have to write
a method which is all of about 8 lines long. Why is that such a
problem? You shouldn't expect .NET to provide you absolutely everything
gift-wrapped: you should expect it to provide you enough tools so that
you can reasonably easily get the effect you want, just as you can
here.


That's the /thing/ about .NET - it can be _very_ useful in some
respects, but in others, it *just* cuts short of the mark. In these
other cases, that fact is a slight annoyance.

An analogy: it's the dream house you've just bought, which initially
appears flawless. But then, one day, while standing in one of the
rooms, the floorboards break through due to lack of strength, and down
you fall. You then need to build a wrapper around this faulty
floorboard, and wonder for how many other floorboards you'll need to do
this.

To be honest, I wouldn't ever complain about .NET if I didn't think it
could handle it.
Nov 15 '05 #14
Julie J. wrote:
You need TryParse -- it attempts the parse, and returns true/false on
success/failure. Problem is that it *only* is available for the double type --
don't ask me why, more .NET shortsightedness...

So, you could do the following:

double result = 0;
int i = double.TryParse(someString, style*, provider*, result) ? (int)result :
0;

A *little* cleaner.

*Define style and provider to your specific needs


Thanks.
Nov 15 '05 #15
C# Learner <cs****@learner.here> wrote:
That's the /thing/ about .NET - it can be _very_ useful in some
respects, but in others, it *just* cuts short of the mark. In these
other cases, that fact is a slight annoyance.

An analogy: it's the dream house you've just bought, which initially
appears flawless. But then, one day, while standing in one of the
rooms, the floorboards break through due to lack of strength, and down
you fall. You then need to build a wrapper around this faulty
floorboard, and wonder for how many other floorboards you'll need to do
this.


The problem with this analogy is that you don't know when the
floorboards are going to break. In the .NET case, it's not like it
fails in an unpredictable way (at least, not in the example you've
given). You don't need to worry about *every* floorboard being faulty -
you just need to write a few lines of code because .NET happens not to
supply the precise behaviour you want all wrapped up in one method
call.

Personally I don't see that as a problem at all.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #16
Try double.TryParse, which returns true or false, and does not throw an
exception.
--Peter
"C# Learner" <cs****@learner.here> wrote in message
news:uT**************@TK2MSFTNGP10.phx.gbl...
Is there a way to avoid the following mess?

int i = 0;
if (someString != null) {
try {
i = Int32.Parse(someString);
} catch (FormatException) {

}
}

More specifically, is there a way of avoiding the ugly empty catch
statement?

Nov 15 '05 #17
The real problem with this issue is the lack of consistency.

The double type has a TryParse, none of the other numeric types do. Why not?

"Jon Skeet [C# MVP]" wrote:

C# Learner <cs****@learner.here> wrote:
That's the /thing/ about .NET - it can be _very_ useful in some
respects, but in others, it *just* cuts short of the mark. In these
other cases, that fact is a slight annoyance.

An analogy: it's the dream house you've just bought, which initially
appears flawless. But then, one day, while standing in one of the
rooms, the floorboards break through due to lack of strength, and down
you fall. You then need to build a wrapper around this faulty
floorboard, and wonder for how many other floorboards you'll need to do
this.


The problem with this analogy is that you don't know when the
floorboards are going to break. In the .NET case, it's not like it
fails in an unpredictable way (at least, not in the example you've
given). You don't need to worry about *every* floorboard being faulty -
you just need to write a few lines of code because .NET happens not to
supply the precise behaviour you want all wrapped up in one method
call.

Personally I don't see that as a problem at all.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 15 '05 #18

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

Similar topics

10
by: teddysnips | last post by:
Application is a Work Tracking/Timesheet database. The increments of work are stored in the TimesheetItem table. This contains, inter alia, the Work Code, the Start and the Duration that the...
4
by: Svend Tofte | last post by:
Hey, I'm doing some webapplications, and in one of them, I want to open a page, from another domain. This is running internally, with full control over the enviroment. However, even adding the...
9
by: Andrew Au | last post by:
Dear all, I am trying to write a piece of software that use Object Oriented design and implement it with C, I did the following == In Object.h == typedef struct ObjectStructure* Object; ...
3
by: collinm | last post by:
hi in a c program, i copy often file on nfs to see if i can see the nfs i do something like: if((exist = stat(mnt_dir, &buf))==0){ if((fp = fopen(tmp_mnt_dir_www, "w"))!=NULL) {
2
by: Samuel | last post by:
Imagine you have the following code: try { ... } catch (ThreadAbortException eThread) { if (WorkStopped != null) WorkStopped(this, EventArgs.Empty) }
1
by: Scott Yost | last post by:
I have a managed class A which I import via a DLL. public __gc class A { public B otherClass; } And another class C which is just in a CPP file - not in the DLL. #include <b.h> class C
13
by: Fei Liu | last post by:
Hi Group, I've got a problem I couldn't find a good solution. I am working with scientific data files in netCDF format. One of the properties of netCDF data is that the actual type of data is only...
44
by: shuisheng | last post by:
Dear All, Assume there are three classes where CA has members of class CA1 and CA2 as follows. To make the public functions of CA1 and CA2 can work on the members a1 and a2 in a CA object, I...
36
by: CK | last post by:
How do I write a set based query? I have a groupSets table with fields setId, idField, datasource, nameField, prefix, active Data: 1,someIDfield, someTable, someField, pre1, 1 2,someotherIDfield,...
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...
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: 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: 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...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
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

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.