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