473,651 Members | 3,012 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 3391
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.WriteLi ne(text.ToStrin g());
}
catch (NullReferenceE xception)
{
Console.WriteLi ne("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 ArgumentExcepti on( ... ) 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


"cashdeskma c" 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 (SomeTypeOfExce ption) {
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**********@g mail.comschrieb im Newsbeitrag
news:O4******** ******@TK2MSFTN GP04.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 (SomeTypeOfExce ption) {
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**********@g mail.comschrieb im Newsbeitrag
news:O4******** ******@TK2MSFTN GP04.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 (SomeTypeOfExce ption) {
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

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

Similar topics

0
2144
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. >-----Original Message----- >Is there any way to output an error directly to the HTML
5
27380
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 that catches an expected exception. The method in the DLL throws the exception back out. When in debug mode, the process just exits.
3
4850
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) serializer.Deserialize(reader); } catch(System.InvalidOperationException ioe) {
3
3207
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 was wondering if there is a way that i can get the name of the function in which the exception has occured like try{} catch(Exception e) { Log.Append(e.FunctionName + "--" + e.Message);
10
5551
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
6973
by: Mr Flibble | last post by:
Are try { //something } catch { // }
7
2482
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
10092
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
4629
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?
0
8361
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8278
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8807
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8701
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
6158
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4144
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4290
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2701
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1588
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.