// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; namespace Exceptions { public static class Luck { private static Random rng = new Random(); public static bool InLuck() { return rng.NextDouble() > 0.2; } } public class XException : Exception { public XException(string msg) : base(msg) { } } public class X : IDisposable { private string id; public X(string id) { if(Luck.InLuck()) { this.id = id; Console.WriteLine("X {0} created", id); } else { throw new XException("Error creating " + id); } } public void Dispose() { Console.WriteLine("X {0} closed", id); } } public class Program { public static void Main(string[] args) { try { using(X o1 = new X("A")) { using(X o2 = new X("B")) { // 20 lines Console.WriteLine("Part 1"); if(!Luck.InLuck()) { throw new XException("Error during execution"); } // 20 lines Console.WriteLine("Part 2"); } } } catch(XException ex) { Console.WriteLine(ex.Message); } } } }