Use C# method attributes for standard exception handling

  • Thread starter Thread starter Koen
  • Start date Start date
K

Koen

Hi,

I have been reading a bit basic stuff about method attributes in C#,
and I wanted to build the following functionality with it:

if a method has the custom attribute <LogException> the method has to
be wrapped as follows:

try
{
// call method
}
catch(System.Exception ex)
{
SaveToDb(ex);
throw ex;
}

Can somebody help me on the way how to implement this kind of
functionality? I'm quite sure this is possible, since i assume the
microsoft exception framework uses the same technique.

Tnx for any help.

Regards,

Koen Appeltans
 
Koen,

I don't quite understand what are you trying to accomplish.
Are you trying to force programmers using this method to put it in a
try/catch or you want the compiler to generate this code for you. Either
ways I don't think you can do it via attributes.


What you can do though, is to add try/catch in your code.
for example:

class Foo
{
public Bar()
{
try
{
BarImp();
}
catch(System.Exception ex)
{
SaveToDb(ex);
throw ex;
}
}

private BarImp()
{
// method implementation.
}
}

The user see Bar method and calling it will log any exception if it happens.
Ofcourse you don't nee to split the implementaiton on Bar and BarImp both
can go in the same method.

Anyways I'd suggest to check out the logging frameworks that are out there
or look at the System.Diagnostics names space and find out how to use
listeners for implementing more flexible logging system.
 
I think that what the OP is after is Java-style forced exception
handling. If that's the case, then no, there is no way to do that in
C#. Not even with exceptions, and no, the compiler doesn't use a
similar mechanism for anything.
 
Hi Stoitcho,

tnx for the response.

your implementation is the way it is done now.
since i'm a bit of a lazy coder, i was wondering if that try catch
statement could be done by an attribute.
now i guess i understood attributes a bit wrong, i thought you could
add code in the beginning and the end of your method with attributes,
but they're meant as some information about the method, a
characteristic.

so i guess i'll simply continue to write the exception code as i did in
the past.

regards,

Koen

Stoitcho Goutsev (100) schreef:
 

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