Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I avoid duplicated try catch blocks

I have several methods that look like this:

public void foo()
{
   try 
   {
      doSomething();
   }
   catch(Exception e)
   {
      Log.Error(e);
   }
 }

Can I change the code to look like?

[LogException()]
public void foo()
{   
   doSomething();
}

How can I implement this custom attribute? and what are the pros and cons of doing it?

-----Edit 1------------

Can I implemented it myself, I mean just write one class, or do I need to use postsharp or another solution?

like image 619
Delashmate Avatar asked Sep 12 '11 06:09

Delashmate


People also ask

How do I stop multiple try catch blocks?

To avoid writing multiple try catch async await in a function, a better option is to create a function to wrap each try catch. The first result of the promise returns an array where the first element is the data and the second element is an error. And if there's an error, then the data is null and the error is defined.

Can there be a catch block without a matching try block?

Core Java bootcamp program with Hands on practiceYes, It is possible to have a try block without a catch block by using a final block. As we know, a final block will always execute even there is an exception occurred in a try block, except System.

Are try catch blocks limited to one catch?

Yes, we can define one try block with multiple catch blocks in Java. Every try should and must be associated with at least one catch block.

Is it possible to have multiple try blocks with one catch block?

You cannot have multiple try blocks with a single catch block. Each try block must be followed by catch or finally. Still if you try to have single catch block for multiple try blocks a compile time error is generated.


1 Answers

You can use delegates and lambdas:

private void ExecuteWithLogging(Action action) {
    try {
        action();
    } catch (Exception e) {
        Log.Error(e);
    }
}

public void fooSimple() {
    ExecuteWithLogging(doSomething);
}

public void fooParameter(int myParameter) {
    ExecuteWithLogging(() => doSomethingElse(myParameter));
}

public void fooComplex(int myParameter) {
    ExecuteWithLogging(() => {
        doSomething();
        doSomethingElse(myParameter);
    });
}

In fact, you could rename ExecuteWithLogging to something like ExecuteWebserviceMethod and add other commonly used stuff, such as checking credentials, opening and closing a database connection, etc.

like image 53
Heinzi Avatar answered Oct 06 '22 15:10

Heinzi