Introduction
These days, I'm concentrating on making my project stronger. I tried to add Try Catch
everywhere I could. I encountered two main problems. The first is that some functions in the common library cannot use main project’s Log system, I finally found a solution for that. The second is that adding code Try {}
+ Catch(Exception){}
takes me too much time, and it occupied lot of lines. I wanted to keep my code clear, so I made an easy trycatch
by Func<T1, T2>
. In my code, you can also use Extension to track your exception easily.
But unfortunately, my code is not very useful because of inefficiency of this method. Instead, use directly with Try Catch
, my code costs 100 times more. And I found that my code is sometimes confusing for developers (who don’t use Action and Func). :(
class Program
{
static void Main(string[] args)
{
Console.ReadLine();
try
{
DataSet ds = new DataSet();
Console.WriteLine(EasyTryCatch(ds));
ds = null;
Console.WriteLine(EasyTryCatchExt(ds));
}
catch (Exception exp)
{
Console.WriteLine(exp.Message);
}
Console.ReadLine();
}
private static string EasyTryCatchExt(DataSet ds)
{
string functionName = "extension";
return ds.Track((s) =>
{
if (s == null)
throw new Exception("Yes " + functionName);
else
return true;
}, "EasyTryCatchExt").ToString();
}
private static string EasyTryCatch(DataSet ds)
{
return ExceptionFunction<DataSet, bool>.RunTrack(((s) =>
{
if (s == null)
throw new Exception("Yes");
else
return true;
}), ds, "EasyTryCatch").ToString();
}
public static class ExceptionFunction<T1, T2>
{
public static T2 RunTrack(Func<T1, T2> func, T1 para, string functionName)
{
try
{
return func(para);
}
catch (Exception exp)
{
throw new Exception(functionName + " : " + exp.Message, exp);
}
}
}
}
public static class ExceptionFunc
{
public static TResut Track<T1, TResut>(this T1 para, Func<T1, TResut> func, string functionName)
{
try
{
return func(para);
}
catch (Exception exp)
{
throw new Exception(functionName + " : " + exp.Message, exp);
}
}
}