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

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 3368
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Francisco Fagas | last post by:
Hi, you can put your code between: try{ }catch(Exception ex){;} in codebehind and your html code: response.write(ex.Message) the last code is in c#, remember that C# is Key sensitive. ...
5
by: David | last post by:
I am having a bit of a problem with catching an exception within a thread. Here is the scenario: I have a Windows Form. I create a new thread. This new thread calls a method in another DLL...
3
by: Pete Davis | last post by:
I've got the following code: try { reader = new StreamReader(configFile); XmlSerializer serializer = new XmlSerializer(typeof(ServerConfig)); config = (ServerConfig)...
3
by: Sunny | last post by:
Hi, I have created a StringBuilder (Log) in my application that appends all the errors and exceptions in my application. I have included Catch blocks at each sensitive location in my functions. I...
10
by: mttc | last post by:
I read articles that suggest preventing delete by throwing Exception from RowDeleting Event. I not understand where I can catch this Error?
7
by: Mr Flibble | last post by:
Are try { //something } catch { // }
7
by: Daimler | last post by:
i am using visual c++ 2005 clr window form with try and catch a serial port readline. the codes are as follows: - try{ Form1::textBox1->Text = Form1::serialPort1->ReadLine();
7
by: suneethadotnet | last post by:
HI, i want to know if there is any exception in finally then how to catch exception in Finally Block.
1
by: bob | last post by:
I have a console application and a timer inside. The timer will throw an Exception while event Elapsed. but i cannot catch this Excepion, How can I catch the Exception?
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...
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...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
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: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
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...
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...

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.