Jamie
Jamie

Reputation: 755

C# Throw being caught in last catch

I'm wondering if my understanding of Exception is incorrect. I have the following code:

try
{
   // ... code calls a function which throws a UASException()
}
catch (UASException ex)
{
    throw;
}
catch (Exception ex)
{
    throw new UASException("An unknown error has occured", ex);
}

Now when I re-throw the UASException it gets caught by the following Catch, is this correct? I thought it should return to the calling code with the re-thrown UASException.

What could I be missing?

Upvotes: 3

Views: 976

Answers (1)

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56747

No it does not. Only one exception handler is picked (the one with the best matching exception type). You could have easily tried, but...


Example: The following code outputs "Catch 1" and not "Catch 2", which is what I'm saying. Only one catch is executed, no matter whether an exception occurs within the catch block. To catch exceptions within a catch block you need to nest catch blocks.

using System;
using System.Collections.Generic;
using System.Text;

namespace CSharp
{
    public class Class1
    {
        public static void Main(string[] args)
        {
           try
           {
              throw new ArgumentException("BANG!");
           }
           catch (ArgumentException)
           {
               Console.WriteLine("Catch 1");
               throw;
           }
           catch
           {
               Console.WriteLine("Catch 2");
           }
        }
    }
}

Upvotes: 2

Related Questions