catch(Exception ex) Vs catch (Exception)

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

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)?
 
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.
 
Hi,
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/archive/2006/09/29/92708.aspx

HTH
Greetings,
Laurent
 
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
 
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
 
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.
 
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
 
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?
 
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
 
Martin said:
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.
 
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".
 
Martin said:
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. :-)
 
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/li...compilerservices.runtimewrappedexception.aspx

Bruce said:
Martin said:
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. :-)
 
Phew! For a minute y'all had me thinking I'd made that up after too many
sugary biscuits ;-p

Marc
 
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 said:
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/li...compilerservices.runtimewrappedexception.aspx

Bruce said:
Martin said:
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. :-)
 
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 said:
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 said:
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/li...compilerservices.runtimewrappedexception.aspx

Bruce said:
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. :-)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top