Skip to content

Instantly share code, notes, and snippets.

@follesoe
Created December 24, 2010 14:30
Show Gist options
  • Select an option

  • Save follesoe/754280 to your computer and use it in GitHub Desktop.

Select an option

Save follesoe/754280 to your computer and use it in GitHub Desktop.
What you need to know about re-throwing exceptions
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
namespace ExceptionTest
{
class DataLayer
{
public static int DoSomething()
{
int a = 10;
int b = 0;
int c = a / b;
return c;
}
}
class BusinessLayer
{
public static int DoSomething()
{
return DataLayer.DoSomething();
}
}
class ServiceLayer
{
/// <summary>
/// Creates a new exception by throwing ex in the catch block.
/// </summary>
public static int DoSomething1()
{
try
{
return BusinessLayer.DoSomething();
}
catch (Exception ex)
{
Log.LogException(ex, "Something crashed...", EventLogEntryType.Error);
throw ex;
}
}
/// <summary>
/// Re-throws the exception by calling throw; in the catch block.
/// </summary>
public static int DoSomething2()
{
try
{
return BusinessLayer.DoSomething();
}
catch (Exception ex)
{
Log.LogException(ex, "Something crashed...", EventLogEntryType.Error);
throw;
}
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine();
try
{
ServiceLayer.DoSomething1();
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("[New exception thrown]");
Console.WriteLine(RemoveLongPath(ex.ToString()));
Console.WriteLine();
}
try
{
ServiceLayer.DoSomething2();
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[Exception from data layer re-thrown]");
Console.WriteLine(RemoveLongPath(ex.ToString()));
Console.WriteLine();
}
}
static string RemoveLongPath(string text)
{
return text.Replace(@"C:\Users\jonasf\Documents\Visual Studio 2005\Projects\ExceptionTest\ExceptionTest\Program.cs", @"C:\Program.cs");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment