Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to efficiently break your code by using exceptions? Example 1: Pokemon exception catching
using System;
namespace FunWithExceptions
{
/*
* 'Vindigator' is an imaginary 3rd-party library that contains
* a lot of useful (if you're into the vindication business) APIs.
*/
public static class Vindigator
{
/// <summary>
/// Return true if the customer is a good customer, false otherwise.
/// </summary>
public static bool IsCustomerAGoodCustomer(Customer customer)
{
if (customer == null)
throw new VindigatorInvalidCustomerException("Something is wrong with your customer!");
if (customer.AmountOwed < 1000)
return true;
return false;
}
}
public class VindigatorInvalidCustomerException : Exception
{
public VindigatorInvalidCustomerException(string message) : base(message)
{}
}
public class Customer
{
public int Id { get; set; }
public string Code { get; set; }
public Decimal AmountOwed { get; set; }
}
public class VindicationReport
{
public Customer Customer { get; set; }
public bool IsGoodCustomer { get; set; }
public Decimal MoneyOwed { get; set; }
}
public class ValuationRates
{
public Decimal PercentageFee { get; set; }
public DateTime ValuationDate { get; set; }
}
public static class MyBusinessApp
{
public static VindicationReport GenerateVindicationReport(Customer customer, ValuationRates rates)
{
var report = new VindicationReport { Customer = customer };
try
{
report.IsGoodCustomer = Vindigator.IsCustomerAGoodCustomer(report.Customer);
if (report.IsGoodCustomer)
report.MoneyOwed = report.Customer.AmountOwed;
else
report.MoneyOwed = report.Customer.AmountOwed + report.Customer.AmountOwed * rates.PercentageFee;
}
catch (Exception)
{
// [Richard] if we get an exception here, it means the customer is null!
// Seems to happen when the main vindication job gets stuck (damn John!). Return a null report in that case.
return null;
}
return report;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment