Inexception

« Return to Article
  • Jerry 2013-02-21 08:04
    Each exception thrown by our application must be caught handled
    That's why all my code starts by defining a catch handle.
  • The_Assimilator 2013-02-21 08:05
    Hey we do that in our code! Except we use a construct called a "while loop" to get all the inner exceptions. I dunno, maybe this way is more enterprise-y?
  • Sam 2013-02-21 08:06
    Shirley this calls for a loop. Or maybe even recursion? Or a loop?? Or recursion???
  • snoofle 2013-02-21 08:07
    OK, I'm not familiar with this construct... are there always that many inner exceptions?
  • Remy Porter 2013-02-21 08:08
    In my experience, you never really need to dig more than a level or two down. To have that many nested levels means that you're being super Enterprise-y.
  • El Fredo 2013-02-21 08:09
    If you dig deep enough in the exception stack, you end in Limbo.
  • keigezellig 2013-02-21 08:10
    TRWTF is the empty catch block. What if the call to MessageBox.Show() fails? (maybe because of the too much nesting :-) )
  • Tom 2013-02-21 08:10
    Sam:
    Shirley this calls for a loop. Or maybe even recursion? Or a loop?? Or recursion???
    MessageBox.Show(WhileLoop.Message || Recursion.Message);
  • LazerFX 2013-02-21 08:11
    Well, TRWTF is this method of catching exceptions, but if you really must...

    catch (Exception ex)
    
    {
    MessageBox.Show(ex.Message);
    while (ex.InnerException != null)
    {
    ex = ex.InnerException;
    MessageBox.Show(ex.Message);
    }
    }
  • Brian Friesen 2013-02-21 08:16
    The original version did use a loop. But, after profiling their application, they determined that the loop was a major performance bottleneck. What you see here is the result of their senior developer's optimization - he unrolled the loop.
  • Kuli 2013-02-21 08:19
    Cool! I'm gonna throw such an exception then:

    ex.InnerException = ex;
  • Pista 2013-02-21 08:20
    C'mon, this is just plain stupid... This can't exist, it's only the result of someone's imagination.
  • Tankster 2013-02-21 08:25
    [quote user="LazerFX"]Well, TRWTF is this method of catching exceptions, but if you really must...

    catch (Exception ex)
    
    {
    MessageBox.Show(ex.Message);
    while (ex.InnerException != null)
    {
    ex = ex.InnerException;
    MessageBox.Show(ex.Message);
    }
    }
    [/quote]

    ... must... refactor...

    catch (Exception ex)
    
    {
    while (ex != null)
    {
    MessageBox.Show(ex.Message);
    ex = ex.InnerException;
    }
    }
    [/quote]

  • MiffTheFox 2013-02-21 08:25

    public class FuckYouException : Exception
    {
    public FuckYouException() : base("Yeah well fuck you too!")
    {
    }

    public override Exception InnerExecption
    {
    get { return this; }
    }
    }
  • JM 2013-02-21 08:28
    keigezellig:
    TRWTF is the empty catch block. What if the call to MessageBox.Show() fails? (maybe because of the too much nesting :-) )


    N'ah it's there in case one of the InnerException's isn't there, resulting in a NullReferenceException when trying to get it's .Message property. After all, why would you check for null when you can just catch all exceptions? And why would MessageBox.Show() ever throw an exception?
  • TGV 2013-02-21 08:41
    I'd call it the Inception...
  • Arvind 2013-02-21 08:43
    El Fredo:
    If you dig deep enough in the exception stack, you end in Limbo.


    He wanted to go deeper. Like a Limbo within a Limbo.
  • ReallyPeople 2013-02-21 08:45
    Would just like to point out the very useful GetBaseException() method :)
  • XXXXXX 2013-02-21 08:46
    Like all great exception reporters, he discarded the stack trace and only showed the message.

    Thumbs Up Man!
  • My Name 2013-02-21 08:51
    Exceptionally bad code can be found everywhere and this code is no exception!
  • Andrew 2013-02-21 08:54
    If we go deep enough, perhaps we will not find an InnerException but throw a NullReferenceException, instead.
  • Phil 2013-02-21 08:55
    Every exception is a null reference exception.
  • Pock Suppet 2013-02-21 09:06
    Sam:
    Shirley this calls for a loop. Or maybe even recursion? Or a loop?? Or recursion???
    No, it doesn't - and don't call me Surely.

    XXXXXX:
    Like all great exception reporters, he discarded the stack trace and only showed the message.

    Thumbs Up Man!
    Yeah, this is sadly standard. We had an error handler that dumped the entire variable context (and since nearly everything is written in the global space, the emails were typically between 3-4MB), but no stack trace - after all, who needs a stack trace when 95% of your code is global? Our MSSQL error handler also routinely ate error messages, queries, etc, but that's more the fault of the MSSQL drivers for Linux...

    Obviously TRWTF is indeed PHP.
  • Bring Back TopCod3r 2013-02-21 09:14
    Pock Suppet:
    Sam:
    Shirley this calls for a loop. Or maybe even recursion? Or a loop?? Or recursion???
    No, it doesn't - and don't call me Surely.

    XXXXXX:
    Like all great exception reporters, he discarded the stack trace and only showed the message.

    Thumbs Up Man!
    Yeah, this is sadly standard. We had an error handler that dumped the entire variable context (and since nearly everything is written in the global space, the emails were typically between 3-4MB), but no stack trace - after all, who needs a stack trace when 95% of your code is global? Our MSSQL error handler also routinely ate error messages, queries, etc, but that's more the fault of the MSSQL drivers for Linux...

    Obviously TRWTF is indeed PHP.


    I bet you had handlers like this too:

    catch(ex)
    {
    // throw the exception
    throw ex;
    }
  • ¯\(°_o)/¯ I DUNNO LOL 2013-02-21 09:16
    MiffTheFox:

    public class FuckYouException : Exception {
      public FuckYouException() : base("Yeah well fuck you too!") {
      }
      public override Exception InnerExecption {
        get { return this; }
      }
    }
    It's InnerExceptions all the way down!

    I'm disappointed that nobody did an InnerFrist post.
  • Marc 2013-02-21 09:17
    It's exceptions, all the way down...
  • lscharen 2013-02-21 09:17
    Tankster:

    ... must... refactor...

    catch (Exception ex)
    
    {
    while (ex != null)
    {
    MessageBox.Show(ex.Message);
    ex = ex.InnerException;
    }
    }



    Another refactor to prevent Kuli and MiffTheFox from exploding your stack...


    catch (Exception ex)
    {
    var visited = new HashSet<Exception>();
    while (ex != null && !visited.Contains(ex))
    {
    visited.Add(ex);

    MessageBox.Show(ex.Message);
    ex = ex.InnerException;
    }
    }
  • Anonymous Paranoiac 2013-02-21 09:23
    Pock Suppet:
    Sam:
    Shirley this calls for a loop. Or maybe even recursion? Or a loop?? Or recursion???
    No, it doesn't - and don't call me Surely.

    XXXXXX:
    Like all great exception reporters, he discarded the stack trace and only showed the message.

    Thumbs Up Man!
    Yeah, this is sadly standard. We had an error handler that dumped the entire variable context (and since nearly everything is written in the global space, the emails were typically between 3-4MB), but no stack trace - after all, who needs a stack trace when 95% of your code is global? Our MSSQL error handler also routinely ate error messages, queries, etc, but that's more the fault of the MSSQL drivers for Linux...

    Obviously TRWTF is indeed PHP.


    Insanity! Such error handling is unexceptable!
  • bkDJ 2013-02-21 09:24
    Tankster:
    ... must... refactor...
    catch (Exception ex)
    
    {
    while (ex != null)
    {
    MessageBox.Show(ex.Message);
    ex = ex.InnerException;
    }
    }

    Pff, the first execution of the while does an unnecessary check in yours.
    catch (Exception ex) {
    
    do {
    MessageBox.Show(ex.Message);
    } while ((ex = ex.InnerException) != null);
    }
  • onitake 2013-02-21 09:30
    <rant>
    TRWTF is the absolutely horrible coding style.

    CamelCase properties, class names, namespaces and sometimes event method names? What a great way to avoid ambiguities!
    Not to mention the amazing space-saving brace placement.
    </rant>
  • ubersoldat 2013-02-21 09:34
    TRWTF is showing the final user (client?) an error which goes down to god knows where in the code and can be shit like:

    throw new Exception("Passing null is for pussies");
    throw new Exception("Shouldn't get here");
    throw new Exception("The process with ID {gibberish} failed because the DB driver for {more gibberish} wasn't found.");

    Not taking into account that non-technical users won't know WTF this means, it's not i18n, so you just added millions of people to your WTF. Oh! And now developers will have to think about nice error messages for their exceptions. And please, don't make your Exceptions i18n, this is EVEN MORE STUPID!

    Next stop for this application will be Error'd
  • Will 2013-02-21 09:37
    Dipshits.

    Exception.ToString() already does this for you.

    Throw this in LinqPad, then stop making fun of stupid people when you're just as fucking dumb.

    new Exception("You",
    new Exception("Are",
    new Exception("Fucking",
    new Exception("Stupid")))).ToString()
  • dgvid 2013-02-21 09:40
    ReallyPeople:
    Would just like to point out the very useful GetBaseException() method :)

    Killjoy! That wipes out all the philosophical nuance by cutting straight to the answer.

    "We demand rigidly defined areas of doubt and uncertainty!"
  • Anonymous Coward 2013-02-21 10:06
    onitake:
    <rant>
    TRWTF is the absolutely horrible coding style.

    CamelCase properties, class names, namespaces and sometimes event method names? What a great way to avoid ambiguities!
    Not to mention the amazing space-saving brace placement.
    </rant>

    pretty sure that's all just standard .NET coding style.
  • Spewin Coffee 2013-02-21 10:26
    Ugh. Exceptions. The out-of-band method of returning a sensible error state wrapped up in so-called "modern programming". Try-catch is rife with pointless issues. The only good thing try-catch can do is automatically restart a program that's crashed.

    A more rational approach is to return a structure from all calls that contains a boolean to indicate success or failure of the call. If successful, the data portion contains the returned data. On failure, the data portion contains a human-readable error message, a machine-friendly error code, and optional data. The programmer is first required to unwrap the result of the call and test for success/failure, which should always be done, but no one does. If the return type enforces checking, the programmer will check it. try-catch doesn't enforce checking - programmers just let exceptions bubble up and they log the error(s) at best.

    But the only languages that can handle that sort of return policy natively are weakly-typed languages (e.g. PHP can implement it via arrays). Strongly-typed languages, usually the sort that require an intermediate compilation stage, have a more difficult time (e.g. C++ could process the return data via macros but it would turn into a complete disaster pretty quickly).
  • Ralph 2013-02-21 10:27
    Pock Suppet:
    MSSQL drivers for Linux
    I just threw up in my mouth a little.

    This is worse than casting pearls before swine. This is more like sitting down to a fine dinner at a restaurant renowned for its excellence, and mixing in a little diarrhea with the salad dressing, just for added flavor.

    I'll leave it to the reader to figure out which end of this interface is the fine food and which part is the diarrhea.
  • DrPepper 2013-02-21 10:35
    Sam:
    Shirley this calls for a loop. Or maybe even recursion? Or a loop?? Or recursion???


    I never write loops; and don't call me Shirley.
  • Walter 2013-02-21 10:35
    MessageBox.Show(ex.Message);
    Why?

    All the user is going to do is play whack-a-mole with your message box anyway.

    To a user, a message box is a barrier between them and what they want to do. The sooner they can get rid of it the better.

    They will commit suicide before they read it. Reading is painful. It might require thought. Expecting someone to think on the job is just inviting a lawsuit.

    It has been demonstrated, even if the message box says in blinking red bold letters "Click OK to format your hard drive and wipe out all your data" they will still click OK.

    That's why security warning pop-ups never work.
  • chubertdev 2013-02-21 10:50
    Each exception thrown by our application must be caught handled before the user sees it.


    Isn't "caught handled" something that happens to teenage boys?
  • chubertdev 2013-02-21 11:03
    Spewin Coffee:
    Ugh. Exceptions. The out-of-band method of returning a sensible error state wrapped up in so-called "modern programming". Try-catch is rife with pointless issues. The only good thing try-catch can do is automatically restart a program that's crashed.

    A more rational approach is to return a structure from all calls that contains a boolean to indicate success or failure of the call. If successful, the data portion contains the returned data. On failure, the data portion contains a human-readable error message, a machine-friendly error code, and optional data. The programmer is first required to unwrap the result of the call and test for success/failure, which should always be done, but no one does. If the return type enforces checking, the programmer will check it. try-catch doesn't enforce checking - programmers just let exceptions bubble up and they log the error(s) at best.

    But the only languages that can handle that sort of return policy natively are weakly-typed languages (e.g. PHP can implement it via arrays). Strongly-typed languages, usually the sort that require an intermediate compilation stage, have a more difficult time (e.g. C++ could process the return data via macros but it would turn into a complete disaster pretty quickly).


    The issue with that is the "data" object will either not be strongly-typed (which, as you pointed out, makes the language a PHP-level WTF), or you would have to extend the return object class for each type that you use, which could lead to a maintenance nightmare. Either way, I'd rather have exceptions. Language developers can try to prevent stupid developers from messing up their own apps, but they will always win, so it's a futile attempt.
  • Excelsior 2013-02-21 11:09
    private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
    {
    ShowException(e.Exception);
    }

    private void ShowException (Exeption myEx)
    {
    if (myEx == null) return;
    MessageBox.Show(myEx.Message);
    ShowException(myEx.InnerException);
    }

    captcha : dolor (it's what i felt reading this WTF and my crappy recursion)
  • Steve The Cynic 2013-02-21 11:14
    Spewin Coffee:
    (e.g. C++ could process the return data via macros but it would turn into a complete disaster pretty quickly).

    C++ could process the return data via an object that (in debug builds, duh) asserts in its destructor that the return value has been looked at.

    It's hard to ensure that the check has actually done something useful, but it will show up in code reviews if you do something like this:

    CheckedError<FlobState> retflob;
    

    retflob = functionCall( stuff );

    retflob.isSuccessful();


    The method name .isSuccessful() is chosen carefully to look weird when it's called outside the context of an if() statement, so that it is easy to spot. (A lesson not learned by the Boost folks, who gave shared_ptr<T> a .get() method rather than the more accurate .sickeninglyBugInducingRawPointerRetrieval(). The only time I ever built a serious smart pointer object, my colleague and I were very purposeful in not giving it a quiet-named raw pointer retrieval method. Sure it had a method that could retrieve the raw pointer, but it was .operator ->(). Nobody much is going to call that explicitly, and anyone seeing such a call will squawk.)

    No, you can't always remove the human element from your code validation process, but you can do things to make that element easier, like grabbing the GAU-8 from your back pocket and using it on anyone who suggests renamiing .sickeninglyBugInducingRawPointerRetrieval() to .get().
  • Spits Coffee Through His Nose 2013-02-21 11:15
    LazerFX:
    Well, TRWTF is this method of catching exceptions, but if you really must...

    catch (Exception ex)
    
    {
    MessageBox.Show(ex.Message);
    while (ex.InnerException != null)
    {
    ex = ex.InnerException;
    MessageBox.Show(ex.Message);
    }
    }


    Now you've done it... Sometimes, the ex.InnerException won't be null, but a self-reference to ex, so you end up with a StackOverflow unless you add a check for ex == ex.InnerException
  • Nexus 2013-02-21 11:26
    The WTFs that give my widescreen monitor a horizontal scrollbar are always the best.
  • chubertdev 2013-02-21 11:31
    Steve The Cynic:
    C++ could process the return data via an object that (in debug builds, duh) asserts in its destructor that the return value has been looked at.

    It's hard to ensure that the check has actually done something useful, but it will show up in code reviews if you do something like this:

    CheckedError<FlobState> retflob;
    

    retflob = functionCall( stuff );

    retflob.isSuccessful();


    The method name .isSuccessful() is chosen carefully to look weird when it's called outside the context of an if() statement, so that it is easy to spot. (A lesson not learned by the Boost folks, who gave shared_ptr<T> a .get() method rather than the more accurate .sickeninglyBugInducingRawPointerRetrieval(). The only time I ever built a serious smart pointer object, my colleague and I were very purposeful in not giving it a quiet-named raw pointer retrieval method. Sure it had a method that could retrieve the raw pointer, but it was .operator ->(). Nobody much is going to call that explicitly, and anyone seeing such a call will squawk.)

    No, you can't always remove the human element from your code validation process, but you can do things to make that element easier, like grabbing the GAU-8 from your back pocket and using it on anyone who suggests renamiing .sickeninglyBugInducingRawPointerRetrieval() to .get().


    I'm out of GAU-8 rounds from the last time I saw developers creating void functions with the prefix "Get", and non-void functions with the prefix "Load."
  • Smouch 2013-02-21 11:34
    The real WTF is using anything other than Exception.ToString()

    Who cares what the exception message is, normally it's wrong/misleading/empty anyway. What you need is a stack trace, which is what ToString generates for you.
  • Valued Service 2013-02-21 11:45
    At first I wondered what would happen if the inner-exception was null, then I noticed in the comments try-catch. Sure enough, it's wrapped in a try-catch.

    ...

    I just don't know what to say now.

    Captcha:
    nimis - Several minis turned inside out.
  • Valued Service 2013-02-21 11:47
    chubertdev:


    I'm out of GAU-8 rounds from the last time I saw developers creating void functions with the prefix "Get", and non-void functions with the prefix "Load."



    public static Object XamlReader.Load(Stream stream)

    http://msdn.microsoft.com/en-us/library/ms590388.aspx

    Time to re'load'
  • operagost 2013-02-21 11:57
    TGV:
    I'd call it the Inception...

    THAT'S THE JOKE
  • operagost 2013-02-21 11:59
    Ralph:
    Pock Suppet:
    MSSQL drivers for Linux
    I just threw up in my mouth a little.

    This is worse than casting pearls before swine. This is more like sitting down to a fine dinner at a restaurant renowned for its excellence, and mixing in a little diarrhea with the salad dressing, just for added flavor.

    I'll leave it to the reader to figure out which end of this interface is the fine food and which part is the diarrhea.

    Perl?
  • chubertdev 2013-02-21 12:04
    Valued Service:
    chubertdev:


    I'm out of GAU-8 rounds from the last time I saw developers creating void functions with the prefix "Get", and non-void functions with the prefix "Load."



    public static Object XamlReader.Load(Stream stream)

    http://msdn.microsoft.com/en-us/library/ms590388.aspx

    Time to re'load'


    The Load ones weren't as bad. If you have it return a bool to say whether or not the operation was successful, I'm not going to be upset.

    But when you prefix a function with "Get", and it doesn't........get, then there are issue. But then again, it was from people who didn't have English as their first language, so I guess the nuances can get lost.
  • Ironside 2013-02-21 12:06
    operagost:
    TGV:
    I'd call it the Inception...

    THAT'S THE JOKE


    I once caught an exception from my realdoll and I can tell you it is no laughing matter.
  • Nagesh 2013-02-21 12:12
    this code is looking fishy to me. not even junior developer from lowest university will do this thing.
  • Nagesh 2013-02-21 12:13
    snoofle:
    OK, I'm not familiar with this construct... are there always that many inner exceptions?


    Will result in endless misery for user.
  • Nagesh 2013-02-21 12:13
    Pista:
    C'mon, this is just plain stupid... This can't exist, it's only the result of someone's imagination.


    Agreed with Pista.
  • Valued Service 2013-02-21 12:17
    Nagesh:
    I can't believe it's not butter.


    throw new NotButterException();
  • herby 2013-02-21 12:19
    Exceptions are for wimps!
    Real programmers don't use exceptions, they use setjmp/longjmp. If the exception was bad enough, then 'exit' with a non-zero argument is in order.

    We now return you to your regularly scheduled pissing match on the virtues of try/catch of which there aren't many!
  • Valued Service 2013-02-21 12:21
    herby:
    Exceptions are for wimps!
    Real programmers don't use exceptions, they use setjmp/longjmp. If the exception was bad enough, then 'exit' with a non-zero argument is in order.

    We now return you to your regularly scheduled pissing match on the virtues of try/catch of which there aren't many!


    Virtue #1 Stacktrace.

    Oh crap, where did my ERR_FILE_NOT_FOUND occur, I use that in 1,500 places. Ok, time to make 1,500 ERR_FILE_NOT_FOUND_XXX error codes, so I know which one. Wait, I'm starting to clash with the ERR_NEED_NEW_DEV_XXX numbers.
  • Paul Neumann 2013-02-21 12:22
    Ironside:
    operagost:
    TGV:
    I'd call it the Inception...

    THAT'S THE JOKE


    I once caught an exception from my realdoll and I can tell you it is no laughing matter.
    I once quoted a comment to replay an unrelated meme and I can tell you it was no laughing matter. People are still naught to laugh about it to this day.
  • Paul Neumann 2013-02-21 12:25
    herby:
    Exceptions are for wimps!
    Real programmers don't use exceptions, they use setjmp/longjmp. If the exception was bad enough, then 'exit' with a non-zero argument is in order.

    We now return you to your regularly scheduled pissing match on the virtues of try/catch of which there aren't many!
    Yes, because all return objects/values should be wrapped in a checked return object. If only we could get a language to support that without all the boilerplate...
  • hashset 2013-02-21 12:40
    lscharen:

    Another refactor to prevent Kuli and MiffTheFox from exploding your stack...


    catch (Exception ex)
    {
    var visited = new HashSet<Exception>();
    while (ex != null && !visited.Contains(ex))
    {
    visited.Add(ex);

    MessageBox.Show(ex.Message);
    ex = ex.InnerException;
    }
    }



    public class FUException : Exception
    {
    private static int i;
    public FUException() { }
    public override Exception InnerExecption { get { return this; } }
    public override bool Equals(object obj) { return false; }
    public override int GetHashCode() { return Interlocked.Increment(i); }
    }
  • Bring Back TopCod3r 2013-02-21 12:53
    hashset:
    lscharen:

    Another refactor to prevent Kuli and MiffTheFox from exploding your stack...


    catch (Exception ex)
    {
    var visited = new HashSet<Exception>();
    while (ex != null && !visited.Contains(ex))
    {
    visited.Add(ex);

    MessageBox.Show(ex.Message);
    ex = ex.InnerException;
    }
    }



    public class FUException : Exception
    {
    private static int i;
    public FUException() { }
    public override Exception InnerExecption { get { return this; } }
    public override bool Equals(object obj) { return false; }
    public override int GetHashCode() { return Interlocked.Increment(i); }
    }


    Clever, but won't compile.
  • 5urd 2013-02-21 13:03

    Exception ex = e.Exception;
    while (ex.InnerException != null) {
    MessageBox.Show(ex.Message);
    ex = ex.InnerException;
    MessageBox.Show(ex.Message);


    The great thing is that it's C# (.NET), so there is no need to free the exception resource! :D
  • Xagyg 2013-02-21 13:04
    I don't think I wanna use GetBaseException()

    public virtual Exception GetBaseException()
    {
    Exception innerException = this.InnerException;
    Exception exception = this;
    for (; innerException != null; innerException = innerException.InnerException)
    exception = innerException;
    return exception;
    }

    Captcha: causa: causa the wonderful things it does!
  • cellocgw 2013-02-21 13:04
    so maybe this function can help (translate to the language of your choice)

    function try_me { trycatch(try_me)}
  • C-Derb 2013-02-21 13:29
    Nagesh:
    Pista:
    C'mon, this is just plain stupid... This can't exist, it's only the result of someone's imagination.
    Agreed with Pista.
    The only possible explanation is that this shoddy code that was inserted for debugging sake and never removed.
  • chubertdev 2013-02-21 13:31

    private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
    {
    LibraryThatSomeoneBuiltSoYouDoNotHaveTo.HandleException(e);
    }
  • hvd 2013-02-21 13:33
    hashset:

    public class FUException : Exception
    {
    private static int i;
    public FUException() { }
    public override Exception InnerExecption { get { return this; } }
    public override bool Equals(object obj) { return false; }
    public override int GetHashCode() { return Interlocked.Increment(i); }
    }

    var visited = new HashSet<Exception>(ReferenceComparer<Exception>.Instance);


    ReferenceComparer is trivially implemented.
  • hashset 2013-02-21 13:36
    Bring Back TopCod3r:
    hashset:
    lscharen:

    Another refactor to prevent Kuli and MiffTheFox from exploding your stack...


    catch (Exception ex)
    {
    var visited = new HashSet<Exception>();
    while (ex != null && !visited.Contains(ex))
    {
    visited.Add(ex);

    MessageBox.Show(ex.Message);
    ex = ex.InnerException;
    }
    }



    public class FUException : Exception
    {
    private static int i;
    public FUException() { }
    public override Exception InnerExecption { get { return this; } }
    public override bool Equals(object obj) { return false; }
    public override int GetHashCode() { return Interlocked.Increment(i); }
    }


    Clever, but won't compile.



    public class FUException : Exception
    {
    private static int i;
    public FUException()
    {
    FieldInfo ha = typeof(Exception).GetField("_innerException", BindingFlags.NonPublic | BindingFlags.Instance);
    ha.SetValue(this, this);
    }
    public override bool Equals(object obj) { return false; }
    public override int GetHashCode() { return Interlocked.Increment(ref i); }
    }

    better?
  • Danno 2013-02-21 13:42
    The real WTF is that you have a code base where exceptions can be thrown and are never handled more than 1 or 2 layers deep.

  • icfantv 2013-02-21 13:50
    oh, it's turtles all the way down...
  • da Doctah 2013-02-21 14:04
    And at the bottom, beneath all the other layer of exceptions, we finally reach the creamy nougat center.
  • chubertdev 2013-02-21 14:29
    How many licks does it take to get to the center of a DispatcherUnhandledExceptionEventArgs.Exception?
  • TGV 2013-02-21 14:32
    operagost:
    TGV:
    I'd call it the Inception...

    THAT'S THE JOKE
    O fucking hell, it's Remi with his incrowd html comments. Why do I even bother. And his writing...

    "Exceptions are a great source of stress and suffering."
    Is that supposed to be ironic? Except that irony is using language that normally signifies the opposite, and here it doesn't.

    "Each exception thrown by our application must be caught handled before the user sees it."
    Applications rarely throw exceptions. Must be caught handled?

    "Failing to do disturbs the balance of our application."
    Failing to follow errors makes.

    "We can use a generic exception handler, but we never can be truly certain we’ve found the true exception."
    Filler stuff, vaguely philosophically sounding.

    "So often the Truth is hidden within an inner exception."
    And one more.

    "It may also be hidden within that exception’s inner exception."
    He gets to the point, except inner exception doesn't make any sense.

    Ok, I'm having a bad hair day...
  • mthamil 2013-02-21 14:36
    There is the Either monad which can provide a way to deal with this kind of situation. The accepted answer to this question is an explanation using Scala: http://stackoverflow.com/questions/1193333/using-either-to-process-failures-in-scala-code
  • Barf 4Eva 2013-02-21 15:05
    Ommmmmmmmmmmmmm
  • ahhhhh 2013-02-21 15:23
    El Fredo:
    If you dig deep enough in the exception stack, you end in Limbo.
    would we call that Exception?
  • NaN (Not a Name) 2013-02-21 15:38
    This is brilliant. It gives devs an incentive not to write code that throws exceptions because they have to click through all of the message boxes.
  • Coyne 2013-02-21 15:58
    XXXXXX:
    Like all great exception reporters, he discarded the stack trace and only showed the message.

    Thumbs Up Man!

    Stack trace? Stack trace? We don't need no steenking stack trace!

    Remy Porter:
    If we go deep enough, perhaps we will not find an InnerException but inner peace, instead.

    Then shouldn't they be referencing property "InnerPeace" in there somewhere?

    I agree with the other guy: I think it very likely what they'll actually get is a null reference exception. No inner peace in this monstrosity. Just a sad (and obscure) end.


  • Sigivald 2013-02-21 16:09
    snoofle:
    OK, I'm not familiar with this construct... are there always that many inner exceptions?


    Nope. That's why it's in a try/catch block!

    This will fire off a NullReferenceException in an awful lot of (almost all?) cases, precisely because of that.
  • chubertdev 2013-02-21 16:17
    NaN (Not a Name):
    This is brilliant. It gives devs an incentive not to write code that throws exceptions because they have to click through all of the message boxes.


    <sarcasm>
    Using the app is a task for users! Any good dev doesn't have to use their app, they just develop it.
    </sarcasm>
  • gizmore 2013-02-21 16:46
    lscharen:
    Tankster:

    ... must... refactor...

    catch (Exception ex)
    
    {
    while (ex != null)
    {
    MessageBox.Show(ex.Message);
    ex = ex.InnerException;
    }
    }



    Another refactor to prevent Kuli and MiffTheFox from exploding your stack...


    catch (Exception ex)
    {
    var visited = new HashSet<Exception>();
    while (ex != null && !visited.Contains(ex))
    {
    visited.Add(ex);

    MessageBox.Show(ex.Message);
    ex = ex.InnerException;
    }
    }


    I propose a change to MiffTheFox's exception.


    public class FuckYouException : Exception
    {
    public FuckYouException() : base("Yeah well fuck you too!")
    {
    }

    public override Exception InnerExecption
    {
    get { return new FuckYouException(this.Message); }
    }
    }


    Code untested and might throw an exception when you compile it.
  • Silverhill 2013-02-21 17:23
    hashset:

    public class FUException : Exception
    {
    private static int i;
    public FUException() { }
    public override Exception InnerExecption { get { return this; } }
    public override bool Equals(object obj) { return false; }
    public override int GetHashCode() { return Interlocked.Excrement(i); }
    }
    FTFY. :-p
  • The Bytemaster 2013-02-21 17:58
    Coyne:

    Remy Porter:
    If we go deep enough, perhaps we will not find an InnerException but inner peace, instead.

    Then shouldn't they be referencing property "InnerPeace" in there somewhere?

    I agree with the other guy: I think it very likely what they'll actually get is a null reference exception. No inner peace in this monstrosity. Just a sad (and obscure) end.
    I went deep enough in Visual Basic .Net and found... Nothing.
  • Matt Westwood 2013-02-21 18:02
    Ralph:
    Pock Suppet:
    MSSQL drivers for Linux
    I just threw up in my mouth a little.

    This is worse than casting pearls before swine. This is more like sitting down to a fine dinner at a restaurant renowned for its excellence, and mixing in a little diarrhea with the salad dressing, just for added flavor.

    I'll leave it to the reader to figure out which end of this interface is the fine food and which part is the diarrhea.


    You'd certainly get a code smell ... OTOH in a French restaurant you'd probably spend an inordinate amount of time trying to identify which cheese you'd been served.
  • noone 2013-02-21 18:03
    The Bytemaster:
    Coyne:

    Remy Porter:
    If we go deep enough, perhaps we will not find an InnerException but inner peace, instead.

    Then shouldn't they be referencing property "InnerPeace" in there somewhere?

    I agree with the other guy: I think it very likely what they'll actually get is a null reference exception. No inner peace in this monstrosity. Just a sad (and obscure) end.
    I went deep enough in Visual Basic .Net and found... Nothing.


    the amount of exceptional programming puns is just too damn high in this post
  • chubertdev 2013-02-21 18:18
    The Bytemaster:
    Coyne:

    Remy Porter:
    If we go deep enough, perhaps we will not find an InnerException but inner peace, instead.

    Then shouldn't they be referencing property "InnerPeace" in there somewhere?

    I agree with the other guy: I think it very likely what they'll actually get is a null reference exception. No inner peace in this monstrosity. Just a sad (and obscure) end.
    I went deep enough in Visual Basic .Net and found... Nothing.


    You String us along, and leave us Empty...
  • Anonymous 2013-02-21 18:31
    TRWTF is the number of commenters who think infinite loops result in stack overflows.
  • Anonymous 2013-02-21 20:35
    "Of course not," the master replied, "the answer to your question is FIVE TONS OF FLAX"


    TRWTF is fnord.
  • Callin 2013-02-21 21:41
    GOTTA CATCH EM ALL
    GOTTA CATCH EM ALL
  • sh code 2013-02-21 23:10
    oh god, so stupid and short-sighted!
    ---

    private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
    {
    bool a = true;
    Exception exc = e.Exception;

    while( a )
    {
    try
    {
    exc = exc.InnerException;
    }
    catch(Exception e)
    {
    a = false;
    }
    }

    MessageBox.Show("Innermost exception: " + exc.Message);
    }


    there. much better!
  • Spider Flyer 2013-02-22 01:19
    Remy Porter:
    In my experience, you never really need to dig more than a level or two down. To have that many nested levels means that you're being super Enterprise-y.


    Unless you are trying to use PowerShell to call a DotNET function, and PowerShell doesn't have a formatting wrapper for an exception thrown by that fuction.

    For example, if you tying to send an email from a script and use the 'Net.Mail.SmtpClient' class to do it, the true error (couldn't connect to mail server) is three levels down the exception chain from the top error 'reflected function call failed.
  • mrputter 2013-02-22 02:12
    lscharen:

    Another refactor to prevent Kuli and MiffTheFox from exploding your stack...


    catch (Exception ex) {
    var visited = new HashSet<Exception>();
    while (ex != null && !visited.Contains(ex))
    {
    visited.Add(ex);

    MessageBox.Show(ex.Message);
    ex = ex.InnerException;
    }
    }


    Sorry, dude. Unsolvability of the halting problem says you can't win that arms race. (Sorry, I haven't used C# in the better part of a decade, so my syntax may be a bit off, but you should get my point.)


    public class FuckYou2Exception : Exception {
    private long n;

    public FuckYou2Exception() : this(0) {}

    public FuckYou2Exception(long n) :
    base("Yeah well fuck you "+new String('u',n)+"!") {
    this.n = n;
    }

    public override Exception InnerExecption {
    get {return new FuckYou2Exception(n+1);}
    }
    }
  • Mike 2013-02-22 02:49
    C-Derb:
    Nagesh:
    Pista:
    C'mon, this is just plain stupid... This can't exist, it's only the result of someone's imagination.
    Agreed with Pista.
    The only possible explanation is that this shoddy code that was inserted for debugging sake and never removed.


    Winner. That's exactly what happened. I'm the original submitter, and it's code that my coworker checked in (claiming it was inadvertent after the fact) for debugging purposes. For some reason, he couldn't attach the debugger to that process, or it wasn't convenient, so he just threw that code together to give him a message box orgy. Of course, there's a thousand different ways to do it better, but that's what he did.

    I assure you, it's very, very real. And from an otherwise competent senior developer to boot.
  • Bill C. 2013-02-22 03:00
    Excelsior:
    private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
    {
    ShowException(e.Exception);
    }

    private void ShowException (Exeption myEx)
    {
    if (myEx == null) return;
    MessageBox.Show(myEx.Message);
    ShowException(myEx.InnerException);
    }
    I made a private ShowException, she made a private ShowInnerException. Then we got caught handled, which sucked.
  • mrputter 2013-02-22 03:30
    Spewin Coffee:
    A more rational approach is to return a structure from all calls that contains a boolean to indicate success or failure of the call. If successful, the data portion contains the returned data. On failure, the data portion contains a human-readable error message, a machine-friendly error code, and optional data.


    Yes!

    Spewin Coffee:
    The programmer is first required to unwrap the result of the call and test for success/failure, which should always be done, but no one does. If the return type enforces checking, the programmer will check it.


    YES!

    Spewin Coffee:
    But the only languages that can handle that sort of return policy natively are weakly-typed languages (e.g. PHP can implement it via arrays).


    Uhhhh... wait.

    Ok, I was with you 110% up to that point.

    This is where a language like (at the risk of coming across as a functional language zealot) Haskell absolutely shines.

    Specifically, the Either type does precisely what you suggest. And far from your disclaimer at the end, Haskell is an extremely strongly-typed language, which does require the caller to, as you suggest, "unwrap the result of the call and test for success/failure."

    So I'm going to present an example in what is not perfectly idiomatic (or best-practice) Haskell, but I've tried to make it clear to a non-reader.

    Assume you have some type called ErrCode - that contains the "machine-friendly error code, and optional data". Other data types I've used should be clear: String, Int and Bool are the obvious things.

    Assume further that you have some process called runComputation that takes 3 Ints (call them x[/], [i]y and z) and returns an Int.

    Finally you have a couple of functions called sanityCheck1 and sanityCheck2 that each take two Ints and return a Bool. The idea being that for the aforementioned x[/], [i]y and z, sanityCheck1 will evaluate the fitness of y in the context of x, and if that's ok, sanityCheck2 will evaluate the fitness of z in the context of y. You've defined a couple of error codes code_check_1_failed and code_check_2_failed to return in the case of failed checks.

    So conceptually we want (using the error-throwing paradigm):
    int doThatThing( int x, int y, int z ) throws ErrCode {
    
    if (! sanityCheck1( x, y )) {
    throw code_check_1_failed;
    }
    if (! sanityCheck2( y, z )) {
    throw code_check_2_failed;
    }
    return runComputation( x, y, z );
    }


    Fine, now to get rid of the throwing up. In Haskell, we can use Either. Either is parametrized by two further types. We say Either a b (with a and b referring to those parametrized types) - meaning that an instance of Either can be one or the other of Left a or Right b. (I'll get to the Left and Right in a minute.)

    In our example, we might want the function doThatThing to return the data type Either (String, ErrCode) Int. This means that the value returned will be one or the other of Left (String, ErrCode) or Right Int.

    The Left and Right are "constructors" - basically a token that we can examine. Based on its value (either Left or Right) we can expect the remainder of the return value to contain either an ordered pair of (String, ErrCode) - which is to say, the human and machine readable error codes - or Int - the actual return value of runComputation.

    So what does this look like? Here's our doThatThing function again:
    doThatThing :: Int -> Int -> Int -> Either (String, ErrCode) Int
    
    doThatThing x y z
    | not (sanityCheck1 x y) = Left ("Sanity check 1 failed.", code_check_1_failed)
    | not (sanityCheck2 y z) = Left ("Sanity check 2 failed.", code_check_2_failed)
    | otherwise = Right (runComputation x y z)


    The first line is the type signature - don't worry too much about it.

    The rest says that we take in x, y and z, then:
    * run sanityCheck1 on x and y - if it fails, return Left followed by the pair of human and machine error codes
    * likewise for sanityCheck2 on y and z
    * if both of the above succeed ("otherwise"), we call runComputation on x, y and z, then wrap the result up in the Right constructor.

    In a real-world usage, of course, runComputation may have its own error codes to potentially return, also wrapped up in an instance of Either. It should go without saying that Haskell has all kinds of facilities to make this trivial to handle.

    So now what about the code that calls it? Well, it would look something like the following:
    ...
    
    case (doThatThing i j k) of
    | Left (str, code) -> putStr str
    | Right answer -> let x' = answer
    in ...


    You call doThatThing on some i, j and k. Then test the answer for Left or Right and do an appropriate thing in either case (in this example, copping out by putStr'ing (which does more-or-less the obvious thing) the human error code and stopping, or by saving the computation result in the variable x' and going on).

    But you have to do something for both cases. To omit one is a semantic error and will generate a compiler error/warning (depending on settings). Haskell's strong typing gives you this: the entire program is type-checked at compile time, and (at least for types like Either), the compiler knows if there is a case you haven't covered.

    Ok, so that was long-winded. And my above disclaimer notwithstanding, I'm really not a functional language zealot. Functional languages are very pretty, but definitely come with their own set of baggage in other areas.

    Are there imperative languages with this kind of typing capability? I honestly don't know, but imagine there must be something somewhere. Possibly some hybrid language like Scala might be a promising place to look?

    Also Google searches along the lines of " imperative parametric polymorphism" or " imperative hindley milner" may prove fruitful.

    Anyway. Yeah. Enough nerding out.
  • Gibbon1 2013-02-22 04:54
    XXXXXX:
    Like all great exception reporters, he discarded the stack trace and only showed the message.

    Thumbs Up Man!


    I usually just spit the entire thing out in a message box. Everyone says that's a horrible unprofessional thing to do. Except the users who never complain about it. They just take a screen shot and email it to me. Fifteen lines of soup at least appears more helpful than 'FILE_NOT_FOUND'

    I have one application *cough* Cadence *cough* Allegro *cough* PCB Designer *cough*. It spits out error numbers when things go wrong. Ask support for a list of error codes and what they mean and they'll admit there is no such list. And since it's just a number, they can't help.
  • forager 2013-02-22 05:57
    It works with toiletpaper..
  • James 2013-02-22 07:13
    right because

    int myFunc(char parm1, int parm2, object* returnValue);

    is totally impossible to do in C/C++. Where object is of whatever type you want to get back; and the int returned by myFunc is either a Boolean or some error error code value. It works almost the same in Java. Strict typing has nothing to do with it.

    The bigger issue comes when you have have to now check all those error results in your code path. If your next action is already conditional your error handling response is any more complex than

    if !(myfunc(...)) {exit(1);}

    the decision trees get pretty large. Have fun debugging that. Exceptions are useful when used well. That fact that most people don't use them well is not a problem with the syntax or language facility; its a problem with you, me, and anyone else who writes sloppy code out there.
  • wombat willy 2013-02-22 08:44
    private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e) { }
  • Omego2K 2013-02-22 08:45
    Gibbon1:
    XXXXXX:
    Like all great exception reporters, he discarded the stack trace and only showed the message.

    Thumbs Up Man!


    I usually just spit the entire thing out in a message box. Everyone says that's a horrible unprofessional thing to do. Except the users who never complain about it. They just take a screen shot and email it to me. Fifteen lines of soup at least appears more helpful than 'FILE_NOT_FOUND'

    I have one application *cough* Cadence *cough* Allegro *cough* PCB Designer *cough*. It spits out error numbers when things go wrong. Ask support for a list of error codes and what they mean and they'll admit there is no such list. And since it's just a number, they can't help.


    Your users send you a screen shot? Could that be a clue you're doing it wrong?
  • lscharen 2013-02-22 09:00
    mrputter:
    lscharen:

    Another refactor to prevent Kuli and MiffTheFox from exploding your stack...
    <snip>


    Sorry, dude. Unsolvability of the halting problem says you can't win that arms race.

    <snip>


    Ok, one more try... ;)


    catch (Exception ex) {
    var visited = new HashSet<Exception>();
    var maxDepth = 10;
    while (ex != null && !visited.Contains(ex) && maxDepth > 0)
    {
    visited.Add(ex);
    maxDepth -= 1;

    MessageBox.Show(ex.Message);
    ex = ex.InnerException;
    }

    if (maxDepth <= 0)
    {
    throw new Exception("Malicious Exception detected. WTF!!!!");
    }
    }
  • EsotericNonsense 2013-02-22 09:55
    This is why exceptions were invented. So you don't have to create a fancy data type just to handle error messages in your program. They actually work pretty good if you use them right. The fact that exceptions are often badly used is not the fault of the construct it's self.
  • chubertdev 2013-02-22 10:53
    James:
    right because

    int myFunc(char parm1, int parm2, object* returnValue);

    is totally impossible to do in C/C++. Where object is of whatever type you want to get back; and the int returned by myFunc is either a Boolean or some error error code value. It works almost the same in Java. Strict typing has nothing to do with it.

    The bigger issue comes when you have have to now check all those error results in your code path. If your next action is already conditional your error handling response is any more complex than

    if !(myfunc(...)) {exit(1);}

    the decision trees get pretty large. Have fun debugging that. Exceptions are useful when used well. That fact that most people don't use them well is not a problem with the syntax or language facility; its a problem with you, me, and anyone else who writes sloppy code out there.


    Maybe something like:


    public DataTable GetCompanies(out bool success) {
    if(success) {
    // proceed as normal
    } else {
    // something went wrong
    }
    }


    Omego2K:
    Your users send you a screen shot? Could that be a clue you're doing it wrong?


    What, you don't like Outlook as an Error Log? :)

    EsotericNonsense:
    This is why exceptions were invented. So you don't have to create a fancy data type just to handle error messages in your program. They actually work pretty good if you use them right. The fact that exceptions are often badly used is not the fault of the construct it's self.


    Exactly.
  • Mike 2013-02-22 12:41
    No there are not, but that is ok, because the exception of no more exceptions will be caught.
  • Ryan 2013-02-22 14:29
    Close, but here's a small refinement...

    catch (Exception ex) {
    while (ex != null) {
    MessageBox.Show(ex.Message);
    ex = ex.InnerException;
    }
    }
  • no laughing matter 2013-02-22 15:21
    EsotericNonsense:
    This is why exceptions were invented. So you don't have to create a fancy data type just to handle error messages in your program. They actually work pretty good if you use them right. The fact that exceptions are often badly used is not the fault of the construct it's self.

    Exceptionally WRONG!

    Exceptions are basically a way to circumvent static type checking.

    A function that declares "returns Cake" states that it only ever will return Cake
    (or null, if you are using one of those billion-dollar-mistake-programming-languages, which Haskell is not part of. Yes you read that right: No null in Haskell!).

    However in programming languages with Exceptions, the function may actually return a Cake, or throw an Exception.

    The "returns Cake" is a lie!

    Which Exception may it return? Well C++ allows even to throw any Object, so the return type of your program has become "returns Mail or any Object".

    And when an Exception is thrown, it is unclear where it will be processed. It might be not processed at all, just ending the program.

    So you lose static type safety and any predictability with Exceptions.

    The Either-Monad, as shown in two other posts before, does not only exist in the functional programming language Haskell and the functional-OO-hybrid Scala (both statically type-checked), but can be also implemented in regular Java.

    (You want that Either-Type only have two subclasses: Left and Right. You can do this by giving Either a private constructor and put the Left- and Right-implementations in the same file as Either).

    However the absence of Lambdas in pre-JDK1.8-Java makes it more awkward to use.
  • jay 2013-02-22 16:09
    keigezellig:
    TRWTF is the empty catch block. What if the call to MessageBox.Show() fails? (maybe because of the too much nesting :-) )


    I think the try/catch is needed because askking for the inner exception when you've already reached the innermost one returns a null, so when you try to go yet another level you throw a null-pointer exception. So they have to catch that and discard it. This is a programming technique called "lazy and lame".
  • jay 2013-02-22 16:16
    "Each exception thrown by our application must be caught handled before the user sees it." Except then it pops up a message box to display the error, which, I would think, means that "the user sees it".

    Well, I suppose you did catch the message before the user sees it. You caught the message, and then promptly displayed it for the user. Thus you caught it before the user saw it. Requirement met. I've got to remember that technique. And remember to question what the word "is" means.

    captcha: appellatio. I'm not sure what it means but I think it's something obscene.
  • Jimmi 2013-02-22 17:09
    Exception.ToString() perhaps?
  • Jimmi 2013-02-22 17:14
    Nice one :D
  • Oh the pain! 2013-02-22 17:16
    Smouch:
    The real WTF is using anything other than Exception.ToString()

    Who cares what the exception message is, normally it's wrong/misleading/empty anyway. What you need is a stack trace, which is what ToString generates for you.

    <rant>

    This. If I had a cent for every "developer" printing/logging ex.Message, and not printing ex.ToString() anywhere, I would be filthy rich.

    And don't get me started with the "that is too ugly for my users, just output ex.Message!!!" folks. Hopeless. Idiots.
    </rant>
  • Jimmi 2013-02-22 17:17
    Will:
    Dipshits.

    Exception.ToString() already does this for you.

    Throw this in LinqPad, then stop making fun of stupid people when you're just as fucking dumb.

    new Exception("You",
    new Exception("Are",
    new Exception("Fucking",
    new Exception("Stupid")))).ToString()


    Beat me to it :)
  • chubertdev 2013-02-22 17:39
    no laughing matter:
    EsotericNonsense:
    This is why exceptions were invented. So you don't have to create a fancy data type just to handle error messages in your program. They actually work pretty good if you use them right. The fact that exceptions are often badly used is not the fault of the construct it's self.

    Exceptionally WRONG!

    Exceptions are basically a way to circumvent static type checking.

    A function that declares "returns Cake" states that it only ever will return Cake
    (or null, if you are using one of those billion-dollar-mistake-programming-languages, which Haskell is not part of. Yes you read that right: No null in Haskell!).

    However in programming languages with Exceptions, the function may actually return a Cake, or throw an Exception.

    The "returns Cake" is a lie!

    Which Exception may it return? Well C++ allows even to throw any Object, so the return type of your program has become "returns Mail or any Object".

    And when an Exception is thrown, it is unclear where it will be processed. It might be not processed at all, just ending the program.

    So you lose static type safety and any predictability with Exceptions.

    The Either-Monad, as shown in two other posts before, does not only exist in the functional programming language Haskell and the functional-OO-hybrid Scala (both statically type-checked), but can be also implemented in regular Java.

    (You want that Either-Type only have two subclasses: Left and Right. You can do this by giving Either a private constructor and put the Left- and Right-implementations in the same file as Either).

    However the absence of Lambdas in pre-JDK1.8-Java makes it more awkward to use.


    I disagree. If the function executes without an exception, the caller then moves on to the next statement. If there is an exception, that propagates up the stack, and the caller has to handle it, or it continues going up the stack.

    Saying that a function "returns an exception" is inaccurate. It may generate one, but not return one.

    However, I do agree with what you said about where an exception is processed. It's just part of the scope of the code. It keeps going up until it is processed. Whether it's by the app that generated the exception, or by the environment that it's running in, something went wrong, and needs to be addressed somewhere.
  • Captain Oblivious 2013-02-22 19:27
    Spewin Coffee:
    Ugh. Exceptions. The out-of-band method of returning a sensible error state wrapped up in so-called "modern programming". Try-catch is rife with pointless issues. The only good thing try-catch can do is automatically restart a program that's crashed.

    A more rational approach is to return a structure from all calls that contains a boolean to indicate success or failure of the call. If successful, the data portion contains the returned data. On failure, the data portion contains a human-readable error message, a machine-friendly error code, and optional data. The programmer is first required to unwrap the result of the call and test for success/failure, which should always be done, but no one does. If the return type enforces checking, the programmer will check it. try-catch doesn't enforce checking - programmers just let exceptions bubble up and they log the error(s) at best.

    But the only languages that can handle that sort of return policy natively are weakly-typed languages (e.g. PHP can implement it via arrays). Strongly-typed languages, usually the sort that require an intermediate compilation stage, have a more difficult time (e.g. C++ could process the return data via macros but it would turn into a complete disaster pretty quickly).


    It sounds like you're looking for Haskell.
  • Exceptions checked here 2013-02-22 20:23
    chubertdev:
    no laughing matter:
    EsotericNonsense:
    This is why exceptions were invented. So you don't have to create a fancy data type just to handle error messages in your program. They actually work pretty good if you use them right. The fact that exceptions are often badly used is not the fault of the construct it's self.

    Exceptionally WRONG!

    Exceptions are basically a way to circumvent static type checking.

    A function that declares "returns Cake" states that it only ever will return Cake
    (or null, if you are using one of those billion-dollar-mistake-programming-languages, which Haskell is not part of. Yes you read that right: No null in Haskell!).

    However in programming languages with Exceptions, the function may actually return a Cake, or throw an Exception.

    The "returns Cake" is a lie!

    Which Exception may it return? Well C++ allows even to throw any Object, so the return type of your program has become "returns Mail or any Object".

    And when an Exception is thrown, it is unclear where it will be processed. It might be not processed at all, just ending the program.

    So you lose static type safety and any predictability with Exceptions.

    The Either-Monad, as shown in two other posts before, does not only exist in the functional programming language Haskell and the functional-OO-hybrid Scala (both statically type-checked), but can be also implemented in regular Java.

    (You want that Either-Type only have two subclasses: Left and Right. You can do this by giving Either a private constructor and put the Left- and Right-implementations in the same file as Either).

    However the absence of Lambdas in pre-JDK1.8-Java makes it more awkward to use.


    I disagree. If the function executes without an exception, the caller then moves on to the next statement. If there is an exception, that propagates up the stack, and the caller has to handle it, or it continues going up the stack.

    Saying that a function "returns an exception" is inaccurate. It may generate one, but not return one.

    However, I do agree with what you said about where an exception is processed. It's just part of the scope of the code. It keeps going up until it is processed. Whether it's by the app that generated the exception, or by the environment that it's running in, something went wrong, and needs to be addressed somewhere.


    This. Also, how do you lose predictability? In any exception-having language I've seen, every single possible exception at any point has a very predictable path. Either it's caught or it's sent up the stack.
  • AN AMAZING CODER 2013-02-22 20:26
    Are glaring grammar errors in the featured articles a meme?
  • hikari 2013-02-23 04:57
    LazerFX:
    Well, TRWTF is this method of catching exceptions, but if you really must...

    catch (Exception ex)
    
    {
    MessageBox.Show(ex.Message);
    while (ex.InnerException != null)
    {
    ex = ex.InnerException;
    MessageBox.Show(ex.Message);
    }
    }


    I believe TRWTF is actually that you would probably be better off just using Exception.GetBaseException() to find the original exception.
  • Dominic 2013-02-23 23:59
    Captain Oblivious:
    Spewin Coffee:
    Ugh. Exceptions. The out-of-band method of returning a sensible error state wrapped up in so-called "modern programming". Try-catch is rife with pointless issues. The only good thing try-catch can do is automatically restart a program that's crashed.

    A more rational approach is to return a structure from all calls that contains a boolean to indicate success or failure of the call. If successful, the data portion contains the returned data. On failure, the data portion contains a human-readable error message, a machine-friendly error code, and optional data. The programmer is first required to unwrap the result of the call and test for success/failure, which should always be done, but no one does.

    It sounds like you're looking for exceptions.

    ftfy
  • chubertdev 2013-02-25 12:04
    hikari:
    I believe TRWTF is actually that you would probably be better off just using Exception.GetBaseException() to find the original exception.


    Half the battle in .NET is knowing the framework and what's already done for you.
  • Mike 2013-02-25 12:42
    Inner piece ... or try to reference a null and die a horrible death like we are trying to avoid by having a generic handler in the first place. Nice.
  • instigator 2013-02-25 14:26
    Please append the error strings and show only one box.
  • instigator 2013-02-25 14:39
    EsotericNonsense:

    This. Also, how do you lose predictability? In any exception-having language I've seen, every single possible exception at any point has a very predictable path. Either it's caught or it's sent up the stack.


    It is often non-obvious when a function will throw an exception, particularly in c# which has no checked exceptions, and particularly if the function you are calling calls an exception throwing function without a try catch. Furthermore, not ending the program can be nice in some cases, but in others it makes debugging tricky. Your program just got into a funny state, and you lost the part of the stack that caused to problem.
  • instigator 2013-02-25 14:43
    Yes, their all idiots for not having complete knowledge the .net API. Everyone should know this, even if they are java or c++ programmers.
  • Richard 2013-02-25 16:30
    lscharen:

    Ok, one more try... ;)


    You don't need to call both Contains and Add on the HashSet; Add will return false if the set already contains the value you're trying to add.

    You also don't need to maintain a separate count of the items you've visited.

    And anyone who writes "throw new Exception" should be boiled in a vat of elephant dung; ALWAYS use a more specific exception type!


    catch (OutOfMemoryException)
    {
    // Nothing you can do with this one.
    throw;
    }
    catch (StackOverflowException)
    {
    // Or this one; your code is doomed.
    throw;
    }
    catch (Exception ex)
    {
    var visited = new HashSet<Exception>(ReferenceEqualityComparer.Instance);
    while (ex != null && visited.Add(ex) && visited.Count < 10)
    {
    MessageBox.Show(ex.Message);
    ex = ex.InnerException;
    }

    if (ex != null)
    {
    throw new YorickHuntException("Malicious Exception detected. WTF!!!!");
    }
    }
  • lscharen 2013-02-25 16:54
    Richard:
    lscharen:

    Ok, one more try... ;)


    <snip insightful and appropriate corrections...>


    All of which goes to show that writing good and correct code, even for seemingly simple tasks like catching an Exception, is almost always much, much more difficult than anyone initially realizes.

  • RandomAnon 2013-02-26 11:38
    Well...
    I guess we now know that an Inception is the deepest INnerexCEPTION posible.

    It all starts with a well placed NullPointerException.

    Tired from luptatum with all these exceptions.
  • Chris 2013-02-27 05:49

    yay for multiple return values.

    http://golang.org/doc/articles/error_handling.html
  • Neil 2013-02-27 12:50
    The original code lends itself to a recursive implementation:
    private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
    
    {
    try
    {
    ShowException(e.Message);
    }
    catch { }
    }

    private void ShowException(Exception ex)
    {
    MessageBox.Show(ex.Message);
    ShowException(ex.InnerException);
    }
    It will usually finish with a null dereference exception unless you throw one of those weird exceptions from earlier comments in which case you'll get a stack overflow or some such.
  • Arancaytar 2013-02-28 10:01
    So I heard you like Exceptions...
  • APolak 2013-03-03 10:56
    The exception handling code is a major performance bottleneck?
    I think something went wrong there.
  • Edgar 2013-03-05 19:18
    <sarcasm>
    Dude I totally agree. I would much rather read code like this:

    if(!FooA())
    goto Error
    if(!FooB())
    goto Error
    if(!FooC())
    goto Error

    return;
    :Error
    HandleError();

    or this:
    if(FooA())
    if(FooB())
    if(FooC())
    return;

    HandleError();

    than to read code like this:
    try{
    FooA();
    FooB();
    FooC();
    }
    catch(Exception e){
    HandleError(e);
    }

    Not to mention code performs so much better when you're constantly checking for error states.
    </sarcasm>
  • TZ 2013-03-06 17:36
    this is sooooo deep.
  • Michael "notriddle" Howell 2013-03-06 22:43
    For C++, you could use boost::variant <http://www.boost.org/doc/libs/1_52_0/doc/html/variant.html>. With destructors, you could even require errors to be "defused" to avoid crashing the program. :P

    For Haskell, not only is the Maybe typeclass a possible solution <https://en.wikibooks.org/wiki/Haskell/Hierarchical_libraries/Maybe>, it's the preferred one.

    More strongly-typed languages should allow this.