469,890 Members | 1,421 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,890 developers. It's quick & easy.

catch(Exception ex) Vs catch (Exception)

Nice and simple one for you all...

Is there a time to use Catch(Exception) rather than creating an instance of
the Exception, as in Catch(Exception ex)?
Oct 13 '06 #1
17 3059
Nice and simple one for you all...
>
Is there a time to use Catch(Exception) rather than creating an
instance of the Exception, as in Catch(Exception ex)?
You don't need to use catch(Exception ex) if you don't want to use an instance
of it. IOW, if you just want to know that a specific exception has occurred
but don't need any of the details, you can omit the ex.

For example:

string text = null;
try
{
Console.WriteLine(text.ToString());
}
catch (NullReferenceException)
{
Console.WriteLine("text is NULL!");
}
Best Regards,
Dustin Campbell
Developer Express Inc.
Oct 13 '06 #2
It depends if you want to do anything with the exception once you've
caught it, or if you want to re-throw it.
On a similar subject, this article explains the difference between
"throw" and "throw ex":

http://mattgollob.blogspot.com/2006/...ifference.html

cashdeskmac wrote:
Nice and simple one for you all...

Is there a time to use Catch(Exception) rather than creating an instance of
the Exception, as in Catch(Exception ex)?
Oct 13 '06 #3
Hi,

cashdeskmac wrote:
Nice and simple one for you all...

Is there a time to use Catch(Exception) rather than creating an instance of
the Exception, as in Catch(Exception ex)?
Both cases do not create an Exception instance. The instance exists, and
was created earlier by calling new ArgumentException( ... ) for example.
Only the "new" keyword really creates objects.

The only difference in the code you show is that, in one case, you get a
reference on the Exception instance (ex), and in the other case you
don't. If you have an instance, and don't use it, you will get a warning
when you compile. That's why you sometimes prefer to use catch (
Exception ), without the "ex".

Such case can occur, for example, when you want to do some clean up when
an error happen:

StreamWriter swr = null;

try
{
// do something
}
catch ( Exception )
{
throw;
}
finally
{
// This code is executed if there is an error or not
if ( swr != null )
swr.Close();
}

In the example above, I don't do anything with the exception, thus I use
( Exception ) without ex. If I wanted to do some logging, or maybe wrap
the Exception in another own one, I would do:

catch ( Exception ex )
{
Trace.WriteLine( ex.Message );
MyOwnException myEx = new MyOwnException( "Error", ex );
throw myEx;
}

In that case, I'd need the reference to ex, so I must declare it.

Also, note that if you re-throw the exception like in the first example,
you should use "throw;" and not "throw ex;". See
http://geekswithblogs.net/lbugnion/a.../29/92708.aspx

HTH
Greetings,
Laurent
--
Laurent Bugnion, GalaSoft
Software engineering: http://www.galasoft-LB.ch
PhotoAlbum: http://www.galasoft-LB.ch/pictures
Support children in Calcutta: http://www.calcutta-espoir.ch
Oct 13 '06 #4
hmm, only if you want to handle all exceptions (or specific one) and do
nothing with them - nor log or show

--
WBR,
Michael Nemtsev :: blog: http://spaces.live.com/laflour

"At times one remains faithful to a cause only because its opponents do not
cease to be insipid." (c) Friedrich Nietzsche


"cashdeskmac" wrote:
Nice and simple one for you all...

Is there a time to use Catch(Exception) rather than creating an instance of
the Exception, as in Catch(Exception ex)?
Oct 13 '06 #5
Further to Dustin's comments...

catch(Exception) {...} is a bit pointless, as you could just use catch
{...} - as *every* exception is : Exception. Also, note that you can throw
without capturing the variable by just saying:

catch (SomeTypeOfException) {
Log("**** Happens"); // or whatever...
throw;
}

Marc
Oct 13 '06 #6
To be accurate, there is e difference between catch() and catch(Exception).
Though not possible in C#; libraries written in other languages could throw
exceptions that don't derive from Exception. This would be caught with
catch() but not with catch(Exception).
Though no wellbehaving library would throw such 'exception', this behaviour
is explicitly stated in the C# specs.

"Marc Gravell" <ma**********@gmail.comschrieb im Newsbeitrag
news:O4**************@TK2MSFTNGP04.phx.gbl...
Further to Dustin's comments...

catch(Exception) {...} is a bit pointless, as you could just use catch
{...} - as *every* exception is : Exception. Also, note that you can throw
without capturing the variable by just saying:

catch (SomeTypeOfException) {
Log("**** Happens"); // or whatever...
throw;
}

Marc

Oct 13 '06 #7
I thought they rationalised that around 2.0 with a wrapper type...

But yes, in 1.1 you definitely can (if you are being nasty)

oh well...

Marc
Oct 13 '06 #8
I'm actually curious about throwing non-exception objects - is it any
more efficient than throwing exceptions? After all, with a
non-exception, all of the traceback information, messages, etc. are
gone. In cases where you just want to use the exception as
flow-control or an alternate-return-value-type (yes, I know these are
both Very Bad Things for exceptions) could such an approach be used for
a non-freakishly-expensive exception?

Christof Nordiek wrote:
To be accurate, there is e difference between catch() and catch(Exception).
Though not possible in C#; libraries written in other languages could throw
exceptions that don't derive from Exception. This would be caught with
catch() but not with catch(Exception).
Though no wellbehaving library would throw such 'exception', this behaviour
is explicitly stated in the C# specs.

"Marc Gravell" <ma**********@gmail.comschrieb im Newsbeitrag
news:O4**************@TK2MSFTNGP04.phx.gbl...
Further to Dustin's comments...

catch(Exception) {...} is a bit pointless, as you could just use catch
{...} - as *every* exception is : Exception. Also, note that you can throw
without capturing the variable by just saying:

catch (SomeTypeOfException) {
Log("**** Happens"); // or whatever...
throw;
}

Marc
Oct 13 '06 #9
Hi,

In addition to what others have said it's easy to know when you should
choose one over the other. If you get a compiler warning saying ex is
never used then use the other syntax. Likewise, if you actually need
to examine the exception then you'd have to include ex.

Brian

cashdeskmac wrote:
Nice and simple one for you all...

Is there a time to use Catch(Exception) rather than creating an instance of
the Exception, as in Catch(Exception ex)?
Oct 13 '06 #10

Martin Z wrote:
I'm actually curious about throwing non-exception objects - is it any
more efficient than throwing exceptions? After all, with a
non-exception, all of the traceback information, messages, etc. are
gone. In cases where you just want to use the exception as
flow-control or an alternate-return-value-type (yes, I know these are
both Very Bad Things for exceptions) could such an approach be used for
a non-freakishly-expensive exception?
First of all, exceptions aren't as terribly expensive as you would
think. See Jon Skeet's article, here:

http://www.yoda.arachsys.com/csharp/exceptions.html

Second, if you were to throw non-exception objects as a flow control
mechanism, nobody maintaining your code would be expecting that, which
would make your code difficult to understand and therefore difficult to
maintain.

Sometimes, coming up with a completely different solution to a familiar
problem is a Bad Thing, not because the solution is technically
unsound, but simply because it's unfamiliar and unexpected.

Oct 13 '06 #11
I realize that. I just ran into this problem when I misunderstood the
2.0 generic dictionary functionality - I was using the idiom:

string myRes
try
{
myRes = dict[someKey];
}
catch (KeyNotFoundException
{
myRes = "MyDefaultString";
}

in C# - and then found out that it had catastrophicly bad performance.
Once I switched over to the TryGet functionality, it behaved much
better. And yet I found myself wishing that I could have just used
exceptions this way. Exceptions provide a nice mechanism for results
that, while not reall "exceptional", don't conform to the primary
return type.

Of course I'd never subject another human being to a bizarre concept of
"alternate return types" as it is a very BadPractice concept. Plus it
mucks up the debugger with lots of "first chance exception" stuff.

I was just curious if it was feasible for my own deepest darkest
hobbyhorse projects. More as a novelty than as a "good idea".

Bruce Wood wrote:
Martin Z wrote:
I'm actually curious about throwing non-exception objects - is it any
more efficient than throwing exceptions? After all, with a
non-exception, all of the traceback information, messages, etc. are
gone. In cases where you just want to use the exception as
flow-control or an alternate-return-value-type (yes, I know these are
both Very Bad Things for exceptions) could such an approach be used for
a non-freakishly-expensive exception?

First of all, exceptions aren't as terribly expensive as you would
think. See Jon Skeet's article, here:

http://www.yoda.arachsys.com/csharp/exceptions.html

Second, if you were to throw non-exception objects as a flow control
mechanism, nobody maintaining your code would be expecting that, which
would make your code difficult to understand and therefore difficult to
maintain.

Sometimes, coming up with a completely different solution to a familiar
problem is a Bad Thing, not because the solution is technically
unsound, but simply because it's unfamiliar and unexpected.
Oct 13 '06 #12

Martin Z wrote:
I realize that. I just ran into this problem when I misunderstood the
2.0 generic dictionary functionality - I was using the idiom:

string myRes
try
{
myRes = dict[someKey];
}
catch (KeyNotFoundException
{
myRes = "MyDefaultString";
}

in C# - and then found out that it had catastrophicly bad performance.
Once I switched over to the TryGet functionality, it behaved much
better. And yet I found myself wishing that I could have just used
exceptions this way. Exceptions provide a nice mechanism for results
that, while not reall "exceptional", don't conform to the primary
return type.

Of course I'd never subject another human being to a bizarre concept of
"alternate return types" as it is a very BadPractice concept. Plus it
mucks up the debugger with lots of "first chance exception" stuff.

I was just curious if it was feasible for my own deepest darkest
hobbyhorse projects. More as a novelty than as a "good idea".
Hey... give it a try. That's how we learn.

Just be sure to post back here with your discoveries. :-)

Oct 13 '06 #13

Thanks to all who replied. That clears things up a bit.
Oct 13 '06 #14
Never mind - non-exception throws are wrapped with a
RuntimeWrappedException in 2.0 - so that is definitely not the way to
dodge the exception expense.

http://msdn2.microsoft.com/en-us/lib...exception.aspx

Bruce Wood wrote:
Martin Z wrote:
I realize that. I just ran into this problem when I misunderstood the
2.0 generic dictionary functionality - I was using the idiom:

string myRes
try
{
myRes = dict[someKey];
}
catch (KeyNotFoundException
{
myRes = "MyDefaultString";
}

in C# - and then found out that it had catastrophicly bad performance.
Once I switched over to the TryGet functionality, it behaved much
better. And yet I found myself wishing that I could have just used
exceptions this way. Exceptions provide a nice mechanism for results
that, while not reall "exceptional", don't conform to the primary
return type.

Of course I'd never subject another human being to a bizarre concept of
"alternate return types" as it is a very BadPractice concept. Plus it
mucks up the debugger with lots of "first chance exception" stuff.

I was just curious if it was feasible for my own deepest darkest
hobbyhorse projects. More as a novelty than as a "good idea".

Hey... give it a try. That's how we learn.

Just be sure to post back here with your discoveries. :-)
Oct 16 '06 #15
Phew! For a minute y'all had me thinking I'd made that up after too many
sugary biscuits ;-p

Marc
Oct 16 '06 #16
No, that's not the problem. this behavior could be switched off by the
RuntimeCompatibilityAttribute. The real problem is, you can't throw them
from C#, (but obviously from C++ ;-).

"Martin Z" <ma***********@gmail.comschrieb im Newsbeitrag
news:11**********************@b28g2000cwb.googlegr oups.com...
Never mind - non-exception throws are wrapped with a
RuntimeWrappedException in 2.0 - so that is definitely not the way to
dodge the exception expense.

http://msdn2.microsoft.com/en-us/lib...exception.aspx

Bruce Wood wrote:
>Martin Z wrote:
I realize that. I just ran into this problem when I misunderstood the
2.0 generic dictionary functionality - I was using the idiom:

string myRes
try
{
myRes = dict[someKey];
}
catch (KeyNotFoundException
{
myRes = "MyDefaultString";
}

in C# - and then found out that it had catastrophicly bad performance.
Once I switched over to the TryGet functionality, it behaved much
better. And yet I found myself wishing that I could have just used
exceptions this way. Exceptions provide a nice mechanism for results
that, while not reall "exceptional", don't conform to the primary
return type.

Of course I'd never subject another human being to a bizarre concept of
"alternate return types" as it is a very BadPractice concept. Plus it
mucks up the debugger with lots of "first chance exception" stuff.

I was just curious if it was feasible for my own deepest darkest
hobbyhorse projects. More as a novelty than as a "good idea".

Hey... give it a try. That's how we learn.

Just be sure to post back here with your discoveries. :-)

Oct 16 '06 #17
That can be done by coding it straight in IL or managed C++, so you
could simply have an assembly providing a static class with the
function ThrowObject(foo), which you use in C#/VB.Net. And the
documentation there for RuntimeCompatibilityAttribute isn't terribly
useful - the example code is conspicuously missing, nor what exactly
the attribute does, or when the wrapping occurs.

Either way, a simple experiment is rapidly becoming complex.

Christof Nordiek wrote:
No, that's not the problem. this behavior could be switched off by the
RuntimeCompatibilityAttribute. The real problem is, you can't throw them
from C#, (but obviously from C++ ;-).

"Martin Z" <ma***********@gmail.comschrieb im Newsbeitrag
news:11**********************@b28g2000cwb.googlegr oups.com...
Never mind - non-exception throws are wrapped with a
RuntimeWrappedException in 2.0 - so that is definitely not the way to
dodge the exception expense.

http://msdn2.microsoft.com/en-us/lib...exception.aspx

Bruce Wood wrote:
Martin Z wrote:
I realize that. I just ran into this problem when I misunderstood the
2.0 generic dictionary functionality - I was using the idiom:

string myRes
try
{
myRes = dict[someKey];
}
catch (KeyNotFoundException
{
myRes = "MyDefaultString";
}

in C# - and then found out that it had catastrophicly bad performance.
Once I switched over to the TryGet functionality, it behaved much
better. And yet I found myself wishing that I could have just used
exceptions this way. Exceptions provide a nice mechanism for results
that, while not reall "exceptional", don't conform to the primary
return type.

Of course I'd never subject another human being to a bizarre concept of
"alternate return types" as it is a very BadPractice concept. Plus it
mucks up the debugger with lots of "first chance exception" stuff.

I was just curious if it was feasible for my own deepest darkest
hobbyhorse projects. More as a novelty than as a "good idea".

Hey... give it a try. That's how we learn.

Just be sure to post back here with your discoveries. :-)
Oct 16 '06 #18

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

reply views Thread by Francisco Fagas | last post: by
5 posts views Thread by David | last post: by
3 posts views Thread by Pete Davis | last post: by
3 posts views Thread by Sunny | last post: by
7 posts views Thread by Daimler | last post: by
1 post views Thread by Waqarahmed | last post: by
reply views Thread by Salome Sato | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.