Skip to content

Instantly share code, notes, and snippets.

@Youenn-Bouglouan
Last active May 22, 2017 20:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Youenn-Bouglouan/1a9d8fe7caf7cb2d81747647edb655d2 to your computer and use it in GitHub Desktop.
Save Youenn-Bouglouan/1a9d8fe7caf7cb2d81747647edb655d2 to your computer and use it in GitHub Desktop.
How to efficiently break your code by using exceptions? Example 2: short-circuiting exception handling
using System;
namespace FunWithExceptions
{
public class FolderCouldNotBeCreatedException : Exception
{
public FolderCouldNotBeCreatedException(string folderPath)
: base("Folder '" + folderPath + "' could not be created!")
{}
}
public static class FileUtils
{
public static string DefaultPath;
public static void CreateFolder(string path, string foldername)
{
// check if the path is valid
if (!IsPathValid(path))
throw new FolderCouldNotBeCreatedException(path + "/" + foldername);
// The rest of logic to create the folder goes here...
}
private static bool IsPathValid(string path)
{
// some complicated logic to determine if the path is valid
return path.Contains("@");
}
}
public static class VindicationUtils
{
// The original method written by Richard
public static void CreateVindicationReportDirectory(string foldername)
{
FileUtils.CreateFolder(FileUtils.DefaultPath, foldername + "_" + DateTime.Today.ToShortDateString());
// The rest of the logic to create the report directory goes here ...
}
// Same method after being refactored by Alexandro
public static void CreateVindicationReportDirectory(string foldername)
{
try
{
FileUtils.CreateFolder(FileUtils.DefaultPath, foldername + "_" + DateTime.Today.ToShortDateString());
}
catch(FolderCouldNotBeCreatedException)
{
throw new InvalidOperationException("Oops! An error occurred during the creation of the report directory.");
}
// The rest of the logic to create the report directory goes here ...
}
}
public static class MyBusinessLogic
{
public static void SetupReportGeneration()
{
try
{
VindicationUtils.CreateVindicationReportDirectory("Customers_Batch1");
// The rest of the init goes here...
}
catch (FolderCouldNotBeCreatedException ex)
{
HandleFailureToCreateMainReportDirectory();
Log(ex);
}
catch (Exception ex)
{
Log(ex);
}
}
private static void HandleFailureToCreateMainReportDirectory()
{
// this method creates a temporary directory to store the reports, in case the main directory couldn't be created
}
private static void Log(Exception ex)
{
// Log the exception to a file and send an email alert to the admin...
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment