Há duas maneiras de tratar uma exception e dar um re-throw na mesma ,abaixo seguem dois trechos de código:
Código 1:
2: {
3:
4: }
5: catch(Exception ex)
6: {
7: throw ex;
8: }
Código 2:
2: {
3:
4: }
5: catch(Exception ex)
6: {
7: throw;
8: }
Quando você usa o código 1,você vair dar um Throw no mesmo objeto Exception e como resultado o stack trace original será perdido.O código 2,mantém o stack trace original e isso é muito útil para debugar.
Um dos guias sobre tratamentos de exceptions diz:
Não de um re-throw jogando o mesmo objeto de exception.Isso faz com que o stack trace original da exception seja perdido;use somente “throw”,para dar um re-throw na exception.
A melhor maneira de ver a diferença,é nesse código de exemplo:
2: {
3: static void Main(string[] args)
4: {
5: try
6: {
7: Method1();
8: }
9: catch (Exception ex)
10: {
11: throw;
12: }
13: }
14:
15: public static void Method1()
16: {
17: Method2();
18: }
19:
20: public static void Method2()
21: {
22: throw new Exception();
23: }
24: }
O seguintestack trace será gerado com o exemplo acima:
at ConsoleApplication2.Program.Method1()
at ConsoleApplication2.Program.Main(String[] args)
at System.AppDomain.ExecuteAssembly(Assembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
Quando você dá um throw em ex;ao invés de throw você recebe:
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
Como você pode ver o stack trace não possui a chamada dos métodos 1 e 2,então quando você usa throw ex,você pede informações essenciais do debug.