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

Avoiding Exceptions

I must be the only one who doesn't think exceptions are the greatest thing
since bread.

Consider the following code:

id = Convert.ToInt32(Request.QueryString["id"]);

First, is there an easy way to tell which methods or properties could
potentially throw an exception? I've scanned the docs and it doesn't seem to
say. Without that knowledge, it's a bit of hit and miss.

Second, knowing that ToInt32() can throw an exception, is there any way to
prevent that? The line above already appears within a try...catch. However,
I don't want the same catch handler to handle problems with this line. I'd
like it handled differently. What other choice is there besides creating an
additional try and/or catch block? And doesn't that seem like overkill?

Thanks.

--
Jonathan Wood
SoftCircuits Programming
http://www.softcircuits.com
Feb 14 '07 #1
11 1709
Jonathan,
>Second, knowing that ToInt32() can throw an exception, is there any way to
prevent that?
If you're targeting .NET 2.0, consider using Int32.TryParse instead of
Convert.ToInt32.
Mattias

--
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Feb 14 '07 #2
Hi Jonathan,

The documentation say what kind of exceptions they might throw. Depending
on what data type you pass to Convert.ToInt32 you might get an
OverflowException, InvalidCastException, ArgumentException or
FormatException, although to know this you have to read the documentation
on every overloaded method. Knowing that Request.QueryString[string] will
return a string narrows it down to a FormatException or OverflowException

For primitive data types there is also a TryParse method that will not
throw an exception, but return true or false to indicate if the parse was
successfull.

int id = 0;
if(!Int32.TryParse(Request.QueryString["id"], out id))
{
// not a valid integer
}
On Wed, 14 Feb 2007 06:36:12 +0100, Jonathan Wood <jw***@softcircuits.com
wrote:
I must be the only one who doesn't think exceptions are the greatest
thing
since bread.

Consider the following code:

id = Convert.ToInt32(Request.QueryString["id"]);

First, is there an easy way to tell which methods or properties could
potentially throw an exception? I've scanned the docs and it doesn't
seem to
say. Without that knowledge, it's a bit of hit and miss.

Second, knowing that ToInt32() can throw an exception, is there any way
to
prevent that? The line above already appears within a try...catch.
However,
I don't want the same catch handler to handle problems with this line.
I'd
like it handled differently. What other choice is there besides creating
an
additional try and/or catch block? And doesn't that seem like overkill?

Thanks.


--
Happy Coding!
Morten Wennevik [C# MVP]
Feb 14 '07 #3
Before Int.TryParse() in 2.0, I did something like below:

public static class FailSafeConvert
{
public static int ConvertToInt( object value, int defaultValue)
{
try
{
Convert.ToInt32(value);
}
catch
{
return defaultValue;
}
}
}

I don't have the coder to hand, if Convert.ToInt32 doesn't take an Object,
then I know I had a similar method ConvertToString() which I may have
wrapped the value up in first.

Regards,

- Paul.

"Jonathan Wood" <jw***@softcircuits.comwrote in message
news:%2****************@TK2MSFTNGP03.phx.gbl...
>I must be the only one who doesn't think exceptions are the greatest thing
since bread.

Consider the following code:

id = Convert.ToInt32(Request.QueryString["id"]);

First, is there an easy way to tell which methods or properties could
potentially throw an exception? I've scanned the docs and it doesn't seem
to say. Without that knowledge, it's a bit of hit and miss.

Second, knowing that ToInt32() can throw an exception, is there any way to
prevent that? The line above already appears within a try...catch.
However, I don't want the same catch handler to handle problems with this
line. I'd like it handled differently. What other choice is there besides
creating an additional try and/or catch block? And doesn't that seem like
overkill?

Thanks.

--
Jonathan Wood
SoftCircuits Programming
http://www.softcircuits.com

Feb 14 '07 #4
I would reccomend doing something like this your structured error
handling is a bunch of crap; and I've always preferred the classic way
to implement error handling

can't Csharp do this?

ROFL

Public Function MyFunction(strIn as string) as string
on error goto errhandler

MyFunction = "Hello World " & strIn

cleanExit:
exit sub
errHandler:
msgbox err.number & " - " & err.description, vbokonly
resume next
End Function


On Feb 13, 9:36 pm, "Jonathan Wood" <j...@softcircuits.comwrote:
I must be the only one who doesn't think exceptions are the greatest thing
since bread.

Consider the following code:

id = Convert.ToInt32(Request.QueryString["id"]);

First, is there an easy way to tell which methods or properties could
potentially throw an exception? I've scanned the docs and it doesn't seem to
say. Without that knowledge, it's a bit of hit and miss.

Second, knowing that ToInt32() can throw an exception, is there any way to
prevent that? The line above already appears within a try...catch. However,
I don't want the same catch handler to handle problems with this line. I'd
like it handled differently. What other choice is there besides creating an
additional try and/or catch block? And doesn't that seem like overkill?

Thanks.

--
Jonathan Wood
SoftCircuits Programminghttp://www.softcircuits.com

Feb 14 '07 #5
Time to call it a day and go home I think - I nearly missed the sarcasm!

<pf******@hotmail.comwrote in message
news:11*********************@j27g2000cwj.googlegro ups.com...
>I would reccomend doing something like this your structured error
handling is a bunch of crap; and I've always preferred the classic way
to implement error handling

can't Csharp do this?

ROFL

Public Function MyFunction(strIn as string) as string
on error goto errhandler

MyFunction = "Hello World " & strIn

cleanExit:
exit sub
errHandler:
msgbox err.number & " - " & err.description, vbokonly
resume next
End Function


On Feb 13, 9:36 pm, "Jonathan Wood" <j...@softcircuits.comwrote:
>I must be the only one who doesn't think exceptions are the greatest
thing
since bread.

Consider the following code:

id = Convert.ToInt32(Request.QueryString["id"]);

First, is there an easy way to tell which methods or properties could
potentially throw an exception? I've scanned the docs and it doesn't seem
to
say. Without that knowledge, it's a bit of hit and miss.

Second, knowing that ToInt32() can throw an exception, is there any way
to
prevent that? The line above already appears within a try...catch.
However,
I don't want the same catch handler to handle problems with this line.
I'd
like it handled differently. What other choice is there besides creating
an
additional try and/or catch block? And doesn't that seem like overkill?

Thanks.

--
Jonathan Wood
SoftCircuits Programminghttp://www.softcircuits.com


Feb 14 '07 #6
Paul Hadfield <no****@noone.comwrote:
Time to call it a day and go home I think - I nearly missed the sarcasm!
I don't think there was any sarcasm involved - see the rest of
pfc_sadr's posts. He's basically trolling...

--
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
Feb 14 '07 #7
Okay, I do see ToInt32() has an Exception section.

And I'll use TryParse().

Thanks.

--
Jonathan Wood
SoftCircuits Programming
http://www.softcircuits.com

"Morten Wennevik [C# MVP]" <Mo************@hotmail.comwrote in message
news:op***************@tr024.bouvet.no...
Hi Jonathan,

The documentation say what kind of exceptions they might throw. Depending
on what data type you pass to Convert.ToInt32 you might get an
OverflowException, InvalidCastException, ArgumentException or
FormatException, although to know this you have to read the documentation
on every overloaded method. Knowing that Request.QueryString[string] will
return a string narrows it down to a FormatException or OverflowException

For primitive data types there is also a TryParse method that will not
throw an exception, but return true or false to indicate if the parse was
successfull.

int id = 0;
if(!Int32.TryParse(Request.QueryString["id"], out id))
{
// not a valid integer
}
On Wed, 14 Feb 2007 06:36:12 +0100, Jonathan Wood <jw***@softcircuits.com>
wrote:
I must be the only one who doesn't think exceptions are the greatest
thing
since bread.

Consider the following code:

id = Convert.ToInt32(Request.QueryString["id"]);

First, is there an easy way to tell which methods or properties could
potentially throw an exception? I've scanned the docs and it doesn't seem
to
say. Without that knowledge, it's a bit of hit and miss.

Second, knowing that ToInt32() can throw an exception, is there any way
to
prevent that? The line above already appears within a try...catch.
However,
I don't want the same catch handler to handle problems with this line.
I'd
like it handled differently. What other choice is there besides creating
an
additional try and/or catch block? And doesn't that seem like overkill?

Thanks.


--
Happy Coding!
Morten Wennevik [C# MVP]
Feb 14 '07 #8
AFAIC, that VB approach is no different from structured exception handling.
I wasn't crazy about that either.

--
Jonathan Wood
SoftCircuits Programming
http://www.softcircuits.com

<pf******@hotmail.comwrote in message
news:11*********************@j27g2000cwj.googlegro ups.com...
>I would reccomend doing something like this your structured error
handling is a bunch of crap; and I've always preferred the classic way
to implement error handling

can't Csharp do this?

ROFL

Public Function MyFunction(strIn as string) as string
on error goto errhandler

MyFunction = "Hello World " & strIn

cleanExit:
exit sub
errHandler:
msgbox err.number & " - " & err.description, vbokonly
resume next
End Function


On Feb 13, 9:36 pm, "Jonathan Wood" <j...@softcircuits.comwrote:
>I must be the only one who doesn't think exceptions are the greatest
thing
since bread.

Consider the following code:

id = Convert.ToInt32(Request.QueryString["id"]);

First, is there an easy way to tell which methods or properties could
potentially throw an exception? I've scanned the docs and it doesn't seem
to
say. Without that knowledge, it's a bit of hit and miss.

Second, knowing that ToInt32() can throw an exception, is there any way
to
prevent that? The line above already appears within a try...catch.
However,
I don't want the same catch handler to handle problems with this line.
I'd
like it handled differently. What other choice is there besides creating
an
additional try and/or catch block? And doesn't that seem like overkill?

Thanks.

--
Jonathan Wood
SoftCircuits Programminghttp://www.softcircuits.com


Feb 14 '07 #9
Jonathan Wood <jw***@softcircuits.comwrote:
AFAIC, that VB approach is no different from structured exception handling.
I wasn't crazy about that either.
So what's your preferred way of handling errors? Every method returning
a value to say whether or not it's succeeded, and using out parameters
for what would otherwise be return values? (i.e. the old C way of doing
things.)

I've seen how badly that worked out - I'm much happier with exceptions,
by and large.

--
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
Feb 14 '07 #10
Jon,
So what's your preferred way of handling errors? Every method returning
a value to say whether or not it's succeeded, and using out parameters
for what would otherwise be return values? (i.e. the old C way of doing
things.)
In some cases, structured exception handling is nice. In particular, in
cases where no error is expected yet many are possible.

But in other cases, such as verifying user input, testing a return value is
far more efficient.
I've seen how badly that worked out - I'm much happier with exceptions,
by and large.
It worked for me; however, as long as it's easy to see which exceptions each
method might raise, and I'm able to find methods such as TryParse() when I
need verify input, then I don't have an issue with it.

--
Jonathan Wood
SoftCircuits Programming
http://www.softcircuits.com
Feb 15 '07 #11
Jonathan Wood <jw***@softcircuits.comwrote:
So what's your preferred way of handling errors? Every method returning
a value to say whether or not it's succeeded, and using out parameters
for what would otherwise be return values? (i.e. the old C way of doing
things.)

In some cases, structured exception handling is nice. In particular, in
cases where no error is expected yet many are possible.

But in other cases, such as verifying user input, testing a return value is
far more efficient.
Which is why TryParse exists. FWIW, I believe the number of places
where exceptions may be thrown but you can usually keep going is
*vastly* lower than the number of places where an exception means "I
want to get way up the stack really quickly and abort the whole large
operation". It's *much* easier to get that right with exceptions than
return codes.
I've seen how badly that worked out - I'm much happier with exceptions,
by and large.

It worked for me; however, as long as it's easy to see which exceptions each
method might raise, and I'm able to find methods such as TryParse() when I
need verify input, then I don't have an issue with it.
Goodo. Java tries to raise awareness of exceptions which might be
thrown by having the concept of "checked exceptions" - if you call a
method which declares that it throws a checked exception, you've either
got to catch that exception yourself, or declare that your method might
throw the checked exception too.

Unfortunately it doesn't work very well in the long run - more and more
Java frameworks are now moving to unchecked exceptions instead.

I'm sure there's a better way yet to be invented, but I'm glad that I
don't have to make every method call part of an "if" statement...

--
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
Feb 15 '07 #12

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

Similar topics

2
by: Steve Jorgensen | last post by:
Hi all, In the code I'm working on to learn Java, I wanted to check to see if a string can be converted to a BigDecimal, and get the BigDecimal value if so. There is no assumption that the...
3
by: Steven Bethard | last post by:
So I have code that looks something like this: def f(xs): for x in xs: y = g(x) # can raise exception AnException for z in h(y): k(z) # can raise a variety of exceptions Now, if g(x) raises...
7
by: cmay | last post by:
FxCop complains every time I catch System.Exception. I don't see the value in trying to catch every possible exception type (or even figuring out what exceptions can be caught) by a given block...
11
by: google_groups3 | last post by:
Hi all. I currently have 2 text files which contain lists of file names. These text files are updated by my code. What I want to do is be able to merge these text files discarding the...
1
by: Anonieko | last post by:
Understanding and Using Exceptions (this is a really long post...only read it if you (a) don't know what try/catch is OR (b) actually write catch(Exception ex) or catch{ }) The first thing I...
8
by: aine_canby | last post by:
>>v = raw_input("Enter: ") Enter: kjjkj Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: 'kjjkj' In my program I need...
17
by: Tony Jackson | last post by:
Hi I'm quite new to C programming - I have more of a Java background: maybe someone here can advise me. I'm nearly finishing a little program but it has some hard-to-find bugs that basically...
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...
4
by: Fernando Rodriguez | last post by:
Hi, I'musing urllib to download pages from a site. How can I detect if a given url is being redirected somewhere else? I want to avoid this, is it possible? Thanks in advance!
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: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.