0

I'm facing a weird issue with catch clause filtered:

catch (System.Net.Http.HttpRequestException ex)
{
    ManagerHelper.Current.ExceptionHandler.Log($"random message",
                log4net.Core.Level.Error, ex: ex);
}
catch (ArgumentNullException ex)
{
    ManagerHelper.Current.ExceptionHandler.Log($"random message for null value",
                log4net.Core.Level.Error, ex: ex);
}
catch (Exception ex) when (!(ex is System.Net.Http.HttpRequestException) && !(ex is ArgumentNullException))
{
    ManagerHelper.Current.ExceptionHandler.Log($"random message for other 
   exception", log4net.Core.Level.Error, ex: ex);
}

Actually when i throw an HttpRequestException the expected behavior would be to enter into the catch of the specific error. For an unknow reason even if the when clause result is false i enter actually into the catch (Exception ex) and not into the catch (System.Net.Http.HttpRequestException ex).

On the immediate window:

!(ex is System.Net.Http.HttpRequestException) && !(ex is ArgumentNullException) => false

Do someone have an explanation of this?

Thanks in advance for your responses and/or advices.

Edited the sample to be more clear.

An other try i did:

 catch (Exception ex)
{
    Type varType = ex.GetType();
    if (ex is System.Net.Http.HttpRequestException)
      ManagerHelper.Current.ExceptionHandler.Log($"random message", log4net.Core.Level.Error, ex: ex as 
      System.Net.Http.HttpRequestException);
    else if (ex is ArgumentNullException)
       ManagerHelper.Current.ExceptionHandler.Log($"random message for null value", log4net.Core.Level.Error, ex: ex as 
       ArgumentNullException); 
    else
       ManagerHelper.Current.ExceptionHandler.Log($"random message for other value", log4net.Core.Level.Error, ex: ex);
}

the varType content is:

{Name = "HttpRequestException" FullName = "System.Net.Http.HttpRequestException"}

The first if result is false and the code is entering in the else statement in debug.

if i do:

varType == typeof(System.Net.Http.HttpRequestException)

The result is true.

3
  • 1
    Based on your assumptions and questions and code logic I recommend you take a step back and read through how the language spec works with try/catch. See try-catch (C# Reference) and How to use the try/catch block to catch exceptions.
    – Igor
    Apr 24, 2020 at 16:07
  • 1
    For a single try with multiple catch, you will only ever transition into one of the catch blocks, and it will be the first one that matches the exception that was thrown. Your when filter is not needed. If one of the catch blocks rethrows the exception, this will bubble up to the next level of try/catch up the call stack, and will not be handled by further catch blocks in the same try/catch level. Apr 24, 2020 at 16:07
  • 1
    ^ What they said. Also,, your when clause actually excludes HttpRequestException (due to the !). so only the final catch will run.
    – John Wu
    Apr 24, 2020 at 16:07

2 Answers 2

16

When I throw an HttpRequestException the expected behavior would be to enter into the catch of the specific error then into the catch without parameter.

Your expectation is completely contrary to reality; I am interested to know how people come to have these sorts of false beliefs about programming languages, so if you have a minute to leave a comment explaining how you came to have this false belief, I would appreciate it.

The precise nature of how your beliefs are wrong is not super clear. It sounds like you believe one of two false things: either (1) every matching catch block executes, not just the first one, or (2) the re-throw in the catch block that is outside the try block causes another catch block "lower down" to be executed.

The documented and designed behaviour of C# with respect to exception handling is that the exception handling process proceeds as follows:

  • The exception is thrown
  • The runtime analyzes the stack to find enclosing try blocks with catch clauses.
  • Stack frames are enumerated in order from most recent to least recent.
  • A stack frame may be associated with a call that has multiple enclosing try blocks with catch clauses around the call site. In that case, try blocks are also examined in order from innermost to outermost.
  • For each enclosing try block with a catch clause, the catch guard clauses are examined in program order, top to bottom.
  • An unguarded catch clause matches everything. A catch clause with a type matches an exception of that type. A catch clause with a filter executes the filter. Note that filters execute before finally blocks.
  • Once the first catch clause that matches is identified, the search stops.

OK, so at this point one of two things has happened. Either we have identified the catch block associated with this exception, or there is no such catch block. If there is no such catch block then program behaviour becomes undefined. The runtime may choose to do a number of things at this point, which includes starting debuggers, running or not running finally blocks, running or not running "unhandled exception" event handlers, and so on. Consult the runtime documentation for the details; this is not covered by the C# specification.

If there is a catch block then we start executing enclosing finally blocks; if they all execute to completion normally then we execute the identified matching catch block, and that's it. No more catch blocks are executed. (If the finally blocks complete with an exception then the whole process starts again of looking for a matching catch.)

The notion that every matching catch block will execute is simply false, so stop believing it. And the notion that a throw in a catch block somehow is caught as though it had been thrown from within the try is also false, so don't believe that either.

If what you want is for the "catch all" block to always run, the way to structure that is:

try 
{
  try
  {
    do the stuff
  }
  catch (your type) when your filter
  {
     do more stuff
     throw; // re-throw to execute the outer "Pokemon" block.
  }
}
catch
{
  now this always runs on exception
}

Does that make sense?

5
  • The throw thing with catch block cascade was a test and not the principal point of my question see the edited subject for more clarifications Apr 24, 2020 at 17:29
  • 1
    @GuillaumeD: Then you should provide us a small program that actually replicates the problem you're having. A complete, runnable program. By shrinking the problem down to something that fits on a page, either you'll figure out the problem or you will provide a program that we can debug. Apr 24, 2020 at 17:37
  • Well i already tested a more simple sample with just a try who throw an HttpRequestException with the same catch structure who work as expected (the catch clause with Typed error is raised). But in my code doesn't. Unfortunatly, knowing it's company code i can't provide a more clear sample. I added more details on the subject. Apr 24, 2020 at 17:47
  • 4
    @GuillaumeD: Then there is something different between the code that works and the code that does not, and if you cannot tell us what that difference is, I'm not sure how we can help you. Apr 24, 2020 at 18:01
  • 1
    The problem maybe thinking of catch as a "kind of if" not a "kind of else if" and an exception being an error object that is retained. Sep 17, 2020 at 18:55
1

You should rewrite your code as a test to prove (or disprove) your understanding. Note in the try block, you can test each exception by uncommenting:

using System;
using System.Net.Http;

namespace junk
{
    class Program
    {
        static void Main(string[] args)
        {
            TestEx();
            Console.ReadKey();
        }

        static void TestEx()
        {
            try
            {
                //throw new HttpRequestException();
                //throw new ArgumentNullException();
                throw new Exception();
            }
            catch (HttpRequestException ex)
            {
                Log(ex, "HttpRequestException");
            }
            catch (ArgumentNullException ex)
            {
                Log(ex, "ArgumentNullException");
            }
            catch (Exception ex) when(!(ex is System.Net.Http.HttpRequestException) && !(ex is ArgumentNullException))
            {
                Log(ex, "Exception");
            }
            catch
            {
                Log("The way I understand it, this really should never be executed.");
            }
        }

        static void Log(string source)
        {
            Console.WriteLine(source);
        }

        static void Log(Exception ex, string source)
        {
            //ManagerHelper.Current.ExceptionHandler.Log($"random message", 
            //log4net.Core.Level.Error, ex: ex);
            Console.WriteLine(source + ": " + ex.Message);
        }
    }
}
2
  • Perhaps your 'completecode' needs to be simplified. I suspect your code is throwing in an area other than where you think it's throwing.
    – sartoris
    Apr 24, 2020 at 17:28
  • I tried already on a more simple example just like yours and it work as expected, that's why i'm pretty surprised about the result in my code. Apr 24, 2020 at 17:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.