Using Try Catch


S

sbalak

I am writing code in C# and I wanted a basic solution:
In Try / Catch block, I want to get a general Exception. So, I write
code as:

try
{
// do something
}
catch (SomethingException ex)
{
// handle ex
}
catch (Exception ex)
{
throw;
}

In the above code, can I write

try
{
}
catch
{
throw;
}

instead of

try
{
}
catch (Exception ex)
{
throw;
}

Please suggest.

Thanks in advance
Santhosh
 
Ad

Advertisements

L

Lenard Gunda

Hi,

If you do not need the exception object itself, you can just specify the
type, so you will not get warnings about unused variables:

catch ( ApplicationException )
{
}
catch ( Exception )
{
}

And yes, you can write a generic catch without arguments, that will
catch everything throwed. Although I think that practice is not
recommended, it will work just fine.

However, if you want to write

try
{
}
catch (SomeException)
{
}
catch
{
throw;
}

You can safely omit the last block, if you only rethrow the exception,
and do not do anything else inside it. If no suitable handler is found,
it will get "rethrown" anyway.


-Lenard
 
Ad

Advertisements

M

Michael Nemtsev

Hello sbalak,

I recomend u to read "Exception Management (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnbda/html/exceptdotnet.asp)"
article. There is everything u should know

s> I am writing code in C# and I wanted a basic solution:
s> In Try / Catch block, I want to get a general Exception. So, I write
s> code as:
s> Please suggest.
s> Thanks in advance
s> Santhosh

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

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

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

Top