Writing error-free code in Visual Basic is a cinch; just tack "On Error Resume Next" up at the top, and you're good to go. But when it comes to Java and C#, it's a bit more of a pain. As Dave found out, you have to wrap every single line with some silly Try/Catch block ...
try { title = service.GetTitle(); } catch {} ... try { appName = query.Item["App_Name"].Trim(); } catch {} ... try { user = requestContext.Identity.User; } catch {}
... sure, it works, but man-oh-man is it ugly. Fortunately, Dave found out about the wonders that are within the System.Reflection namespace and developed much cleaner code ...
title = tryMethod(service,"GetTitle"); ... appName = tryProperty(query, "Item", "App_Name") appName = tryMethod(appName, "Trim") ... user = tryProperty( tryProperty(requestContext, "Identity"), "User" );
That technique seemed to work much better. However it did have the distinct disadvantage of requiring some code to be kept in strings rather than in code. That, and it got really ugly with complex expressions. Fortunately, with the advent of .NET 2.0, Dave was able to come up with a nice, clean solution to the problem of error-ridden code ...
public delegate T SafeCodeDelegate<T>(); class Utility { public static T TryCode<T>(SafeCodeDelegate<T> d) { T returnValue = default(T); try { returnValue = d(); } catch { } return (returnValue); } } ... title = Utility.TryCode<string>(delegate {return service.GetTitle();}); ... appName = Utility.TryCode<string>(delegate {return query.Item["App_Name"].Trim();}); ... user = Utility.TryCode<string>(delegate {return requestContext.Identity.User;});
Thankfully, Petr Lazecky was able to step before this eclipsed to the next level of WTF and impacted a serious project. But it certainly is an interesting example of just how far one can go down the wrong path with creative invention ...