A Try-Catch Block Macro equivalent in C#? - c#

Here is a sample C++ macro that I use to make my code more readable and reduce the Try-Catch Clutter:
#define STDTRYCATCH(expr) \
try { \
return (expr); \
} \
catch (const std::exception& ex) { \
handleException(ex); \
} \
catch (...) { \
handleException(); \
}
Which can be used as:
int myClass::Xyz()
{
STDTRYCATCH(myObj.ReadFromDB());
}
Please note that I'm looking for STDTRYCATCH that handles any code stub we enclose with it.Is there an equivalent in C# ?

You can write helper:
public static class ExcetpionHandler
{
public static void StdTryCatch(this object instance, Action act)
{
try
{
act();
}
catch (Exception ex)
{
var method = instance.GetType().GetMethod("StdException");
if (method != null)
{
method.Invoke(instance, new object[] {ex});
}
else
{
throw;
}
}
}
}
Usage:
public class MyClass
{
public void StdException(Exception ex)
{
Console.WriteLine("Thrown");
}
public void Do()
{
this.StdTryCatch(() =>
{
throw new Exception();
});
}
}
and:
class Program
{
static void Main(string[] args)
{
var instance = new MyClass();
instance.Do();
}
}
But it is not recommeded - due to performance reasons etc - like mentioned in comments.
EDIT:
Like cdhowie mentioned, you can also prepare inteface:
public interface IExceptionHandler
{
void StdException(Exception ex);
}
Then:
public static class ExcetpionHandler
{
public static void StdTryCatch(this IExceptionHandler instance, Action act)
{
try
{
act();
}
catch (Exception ex)
{
instance.StdException(ex);
}
}
}
Your class then need to impelement that interface.

Related

C# Passing a reference to a generic method to another method

I have a program that calls dozens of methods with varying signatures, but the exception handling inside each one is identical. Is there some way to define a method that can accept a reference to a generic method with various signatures (which rules out a Delegate - right?) and return the object, or void that the method requires? I'm using .NET 4.72.
Here is stripped down version of what I'm currently doing and some pseudo-code of what I'd like to do:
static class StackOverflowQuestion
{
public static void Main(string[] args)
{
// What I'm currently doing:
MethodOne("x");
int ret = MethodTwo(0);
//.
//.
//.
MethodNineteen();
// what I'd like to do is replace MethodOne(), MethodTwo(), ..., Method Nineteen()
// with something like:
RunMethod<void>(MethodOneWork, new object[] {"x"});
ret = RunMethod<int>(MethodTwoWork, new object []{1});
//.
//.
//.
RunMethod<void>(MethodNineteenWork, null);
}
private static void MethodOne(string st)
{
try
{
// the try clause is the only difference between the methods
MethodOneWork(st);
}
catch (MyExceptionA)
{
HandleExceptionA();
return;
}
catch(MyExceptionB)
{
HandleExceptionB();
}
catch(Exception)
{
HandleGenericException();
}
}
private static int MethodTwo(int v)
{
try
{
return MethodTwoWork(v);
}
catch (MyExceptionA)
{
HandleExceptionA();
return -1;
}
catch (MyExceptionB)
{
HandleExceptionB();
return -2;
}
catch(Exception)
{
HandleGenericException();
return 0;
}
}
private static void MethodNineteen()
{
try
{
MethodNineteenWork();
}
catch (MyExceptionA)
{
HandleExceptionA();
return;
}
catch (MyExceptionB)
{
HandleExceptionB();
}
catch(Exception)
{
HandleGenericException();
}
}
/// <summary>
/// Run generic method with generic signature
/// </summary>
private static <T> RunMethod(Delegate MethodxWork, object[] myParams)
{
try
{
new <T>() retVal = MethodxWork(myParams);
return retVal;
}
catch (MyExceptionA)
{
HandleExceptionA();
return new <T>();
}
catch (MyExceptionB)
{
HandleExceptionB();
return new <T>();
}
catch(Exception)
{
HandleGenericException();
return new <T>();
}
}
private static void HandleExceptionB()
{
//handle it
}
private static void HandleExceptionA()
{
//handle it
}
private static void HandleGenericException()
{
//handle it
}
}
internal class MyExceptionB : Exception
{
}
internal class MyExceptionA : Exception
{
}
Sure, just create a few methods whose job it is to handle the exceptions, one for returning results and the other for void, and provide something that does your work.
T Handle<T>(Func<T> call)
{
try
{
return call();
}
catch(YourException ex)
{
return default;
}
}
void Handle(Action call)
{
try
{
call();
}
catch(YourException ex)
{
}
}
After that, you can call your other methods with varying signatures inside there.
var result = Handle(() => SomeCallWithVaryingSignature(...));
Handle(() => SomeOtherCall(...));

Does method overload work with exception types?

using System;
// Custom Exception types
class AException : Exception
{
}
class BException : Exception
{
}
class Test
{
public static void Main(string[] args)
{
try
{
throw new AException();
}
catch (Exception ex)
{
Callme(ex);
}
}
public static void Callme(AException aexception) {}
public static void Callme(BException bexception) {}
public static void Callme(Exception ex) {}
}
Callme(ex) will always call Callme(Exception ex) instead of Callme(AException ..) .. Is this an expected behavior. I read method overload resolution do work with inheritance relationships.
there is a more accepted way of doing this. try the following:
try
{
throw new AException();
}
catch (AException aex)
{
Callme(aex);
}
catch (BException bex)
{
Callme(bex);
}
catch (Exception ex)
{
Callme(ex);
}

Design pattern for handling if else with different implementations

I have the following two types of processors
public interface IDefaultProcessor1
{
void Process(IProcess p);
}
public interface IDefaultProcessor2
{
T Process<T>(IProcess p);
}
public class DefaultProcessor : IDefaultProcessor1
{
public void Process(IProcess p)
{
try
{
foreach ...
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
}
}
public class AnotherProcessor : IDefaultProcessor2
{
public T Process<T>(IProcess p)
{
try
{
foreach ...
return p.Result()...
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
}
}
Most of the implementation code is exactly the same (error checking etc) except one returns a value. Is there a pattern to clean this up?
Yes, there is.
Define both methods on the same interface:
public interface IDefaultProcessor
{
void Process(IProcess p);
TResult Process<TResult>(IProcess p);
}
And then:
public class DefaultProcessor : IDefaultProcessor
{
public void Process(IProcess p)
{
DoProcess(p);
}
public TResult Process<TResult>(IProcess p)
{
object result = DoProcess(p);
return (TResult)result;
}
private object DoProcess(IProcess p)
{
try
{
foreach ...
return p.Result();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
}
}
There are many ways you can do this. One thing you have to keep in mind is that there is no way you can have a method with a optional return. That been said, you can try one of the aproaches below:
Implement Template Pattern and return null to your process that don't return anything:
public abstract class AbstractProcess<T>
{
public abstract T DoProcess();
public T Process()
{
//do your common tasks
return DoProcess();
}
}
public class Process1 : AbstractProcess<Process1>
{
public override Process1 DoProcess()
{
return new Process1();
}
}
public class Process2 : AbstractProcess<Process2>
{
public override Process2 DoProcess()
{
return null;
}
}
Create an Interface with both methods, and then choose what is the best method to call (as pointed by Matias CĂ­cero)
public interface IProcessor
{
T Process<T>();
void Process();
}
public class Processor : IProcessor
{
public void Process()
{
DoWork();
}
public T Process<T>()
{
return (T)DoWork();
}
public object DoWork()
{
// do your common tasks
}
}
Create an Interface with a single method and decide if you will return something (or null) based on the type:
public interface IProcessor
{
T Process<T>() where T : class;
}
public class Processor : IProcessor
{
public T Process<T>() where T : class
{
var result = (T)DoWork();
if (typeof(T) == typeof(Process2))
return result;
return null;
}
public object DoWork()
{
// do your common tasks
}
}

Create custom validation attributes c# server side

I'm trying to create Validation Attribute to enforce licensing in my solution.
The way I've tried to do it is using by LicenseValidationAttribute that inherits from ValidationAttribute.
The main goal is when CreateProject() method is called, if the customer already reached the limit of projects he is entitled for, that will lead to exception throwing. else, that will be OK flow.
I've write a small program but unfortunately it doesn't work, means it doesn't throws exception.
The program:
[AttributeUsage(AttributeTargets.Method)]
public class MyValidationAttribute : ValidationAttribute
{
public MyValidationAttribute()
{
}
public override bool IsValid(object value)
{
int id = (int)value;
if (id > 0)
return true;
throw new Exception("Error");
}
}
public class Service
{
[MyValidation]
public bool GetService(int id)
{
if (id > 100)
{
return true;
}
return false;
}
}
static void Main(string[] args)
{
try
{
Service service = new Service();
service.GetService(-8);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message); ;
}
}
Thanks!
After adding System.reflection's GetCustomAttributes method call it works:
static void Main(string[] args)
{
try
{
Service service = new Service();
service.GetService(-8);
service.GetType().GetCustomAttributes(false);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message); ;
}
}

try/catch doesn't work over using statement

try
{
using (response = (HttpWebResponse)request.GetResponse())
// Exception is not caught by outer try!
}
catch (Exception ex)
{
// Log
}
EDIT:
// Code for binding IP address:
ServicePoint servicePoint = ServicePointManager.FindServicePoint(uri);
servicePoint.BindIPEndPointDelegate = new BindIPEndPoint(Bind);
//
private IPEndPoint Bind(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount)
{
IPAddress address;
if (retryCount < 3)
address = IPAddress.Parse("IPAddressHere");
else
{
address = IPAddress.Any;
throw new Exception("IP is not available,"); // This exception is not caught
}
return new IPEndPoint(address, 0);
}
I could imagine this can happen if you are creating a separate thread within the using block. If an exception is thrown there, be sure to handle it there as well. Otherwise, the outer catch block in this case won't be able to handle it.
class TestClass : IDisposable
{
public void GetTest()
{
throw new Exception("Something bad happened"); // handle this
}
public void Dispose()
{
}
}
class Program
{
static void Main(string[] args)
{
try
{
using (TestClass t = new TestClass())
{
Thread ts = new Thread(new ThreadStart(t.GetTest));
ts.Start();
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
}
Do you have more code after the using? The using needs one statement or a block { } after the using statement. In the example below any exception inside the using statement will be caught with the try..catch block.
try
{
using (response = (HttpWebResponse)request.GetResponse())
{
....
}
}
catch (Exception ex)
{
}
This works fine. You'll see an exception getting printed by the Console.WriteLine()
class Program
{
static void Main(string[] args)
{
Foo foo = new Foo();
try
{
using (Bar bar = foo.CreateBar())
{
}
}
catch(Exception exception)
{
Console.WriteLine(exception.Message);
}
}
}
public class Foo
{
public Bar CreateBar()
{
throw new ApplicationException("Something went wrong.");
}
}
public class Bar : IDisposable
{
public void Dispose()
{
}
}
And if you meant that the exception gets thrown inside the using, this works fine to. This will also generate a Console statement:
class Program
{
static void Main(string[] args)
{
Foo foo = new Foo();
try
{
using (Bar bar = foo.CreateBar())
{
throw new ApplicationException("Something wrong inside the using.");
}
}
catch(Exception exception)
{
Console.WriteLine(exception.Message);
}
}
}
public class Foo
{
public Bar CreateBar()
{
return new Bar();
// throw new ApplicationException("Something went wrong.");
}
}
public class Bar : IDisposable
{
public void Dispose()
{
}
}
The using keyword is the same as try-catch-finally, http://msdn.microsoft.com/en-us/library/yh598w02.aspx. Basically, you have a try-catch-finally nested inside of a try-catch which is why you're probably so confused.
You could just do this instead...
class Program
{
static void Main(string[] args)
{
HttpWebResponse response = new HttpWebResponse();
try
{
response.GetResponse();
}
catch (Exception ex)
{
//do something with the exception
}
finally
{
response.Dispose();
}
}
}

Categories