Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One Exception handler for all exceptions of a CLASS

Tags:

c#

exception

I have a class with number of methods and want to have one exception handler for them all. There are so many of these methods and they have different parameters, that it would be ugly to write try/catch for each of them.

Do you maybe know a way where I can do it with having a one in class exception handler, which will handle them all.

UPDATE:


Many of you ask me why. The reason is that I am calling a data source with various methods. so my class has functions getData1, gedData2, getData3,getData4, ...., getDataN. The problem is that there is no way to check if the connection is still open and creating new connection is very very expensive. So I am trying to reuse connection and if the connection on the next call has failed, i would catch this and reconnect and try again. That is why i need this try/catch all block.

to do this for all the functions:

try{    
   datasource.getData()
}
catch(ConnectionException)
{
   datasource.Connect();
   datasource.getData()
}

Thanks

like image 711
husayt Avatar asked Aug 03 '09 11:08

husayt


People also ask

Which is used to handle all exceptions is?

Throwable. The Master Exception Class extends Throwable : java. lang.

Which is used to handle all exceptions in Java?

Java provides two different options to handle an exception. You can either use the try-catch-finally approach to handle all kinds of exceptions. Or you can use the try-with-resource approach which allows an easier cleanup process for resources.

Which is the universal exception handler?

Which is the universal exception handler class? Explanation: Any type of exception can be handled by using class Exceptions. An object of this class is created which can manipulate the exception data. The data can be used to display the error or to run the program further based on error produced.

Can we handle all exceptions in Java?

yeah. Since Exception is the base class of all exceptions, it will catch any exception.


4 Answers

You could use a delegate to pass your method's code into a single try catch like the following example:

    private void GlobalTryCatch(Action action)
    {
        try
        {
            action.Invoke();
        }
        catch (ExpectedException1 e)
        {
            throw MyCustomException("Something bad happened", e);
        }
        catch (ExpectedException2 e)
        {
            throw MyCustomException("Something really bad happened", e);
        }
    }

    public void DoSomething()
    {
        GlobalTryCatch(() =>
        {
            // Method code goes here
        });
    }
like image 82
Jack Allan Avatar answered Oct 18 '22 06:10

Jack Allan


I can't figure out any reason why you may benefit from handling all the exceptions in a class using a single method (can you elaborate? I'm curious...)

Anyway, you can use AOP (Aspect Oriented Programming) techniques to inject (statically or at runtime) exception handling code around the methods of your class.

There's a good assembly post-processing library called PostSharp that you can configure using attributes on the methods in your class:

You may define an aspect like this (from PostSharp website):

public class ExceptionDialogAttribute : OnExceptionAspect
{
    public override void OnException(MethodExecutionEventArgs eventArgs)
    {
        string message = eventArgs.Exception.Message;
        MessageBox.Show(message, "Exception");
        eventArgs.FlowBehavior = FlowBehavior.Continue;
    }
}

And then you'll apply the attribute to the methods you want to watch for exceptions, like this:

public class YourClass {

    // ...

    [ExceptionDialog]
    public string DoSomething(int param) {
        // ...
    }
}

You can also apply the attribute to the whole class, like this:

[ExceptionDialog]
public class YourClass {
    // ...
    public string DoSomething(int param) {
        // ...
    }
    public string DoSomethingElse(int param) {
        // ...
    }
}

This will apply the advice (the exception handling code) to every method in the class.

like image 39
Utaal Avatar answered Oct 18 '22 08:10

Utaal


Exceptions are not really class related but method/callstack oriented. An object should, in general, not try to handle exceptions from it's own methods. It's up to the callers of those methods.

like image 42
Henk Holterman Avatar answered Oct 18 '22 08:10

Henk Holterman


I don't think there is. You could move the try/catch to the caller, but that's not very good design. It may be better to separate it out into another class, and use Reflection to call the methods, like this:

public class MyClass {}
public class MySafeClass {
    public void CallMethod(string name, object[] param) {
        Type t = typeof(MyClass);
        MyClass mc = new MyClass();
        try {
            t.GetMethod(name).Invoke(mc, param);
        }
        catch {
            //...;
        }
    }

}

But you shouldn't! It's not very good practice.

Another method is still using try/catch but having a single method to throw exceptions, etc back to the user:

public class MyClass {
    void DoException(string message) {
        throw new Exception(message);
    }
}

But that still isn't that good an option.

I don't see why it would be ugly - even if you just wrap the whole method in one try/catch with a message. That might be feasible.

It's also a better option to just leave them and pass them back up to the caller, perhaps in try/finally.

It's not exactly hard to try/catch everything, especially with the snippets in Visual Studio and SharpDevelop.

like image 41
Lucas Jones Avatar answered Oct 18 '22 07:10

Lucas Jones