Click here to Skip to main content
15,881,424 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi there . i write following code :
catch (SocketException se)
            {
                if (se.SocketErrorCode == SocketError.TimedOut)
                {
                    //my logic
                }
            }
            catch (WebException we)
            {

            }

and want to catch socket exception first(InnerException of WebException in my condition).
but it doesn't occur. how can do it without inner of WebException block?
thanks

What I have tried:

catch (SocketException se)
            {
                if (se.SocketErrorCode == SocketError.TimedOut)
                {
                    //my logic
                }
            }
            catch (WebException we)
            {

            }
Posted
Updated 11-Apr-17 9:54am

If you're using C# 6 (Visual Studio 2015 or later), you can use an exception filter:
C#
catch (WebException we) when (we.InnerException is SocketException)
{
    var se = (SocketException)we.InnerException;
    if (se.SocketErrorCode == SocketError.TimedOut)
    {
        ...
    }
}
catch (WebException we)
{
    ...
}


If you're using C# 7 (Visual Studio 2017), you can simplify that by combining an exception filter with pattern matching:
C#
catch (WebException we) when (we.InnerException is SocketException se)
{
    if (se.SocketErrorCode == SocketError.TimedOut)
    {
        ...
    }
}
catch (WebException we)
{
    ...
}

Or even:
C#
catch (WebException we) when (we.InnerException is SocketException se && se.SocketErrorCode == SocketError.TimedOut)
{
    ...
}
catch (WebException we)
{
    ...
}


In earlier versions, C# didn't support exception filters. You'll have no choice but to catch the outer exception and test the inner exception:
C#
catch (WebException we)
{
    var se = we.InnerException as SocketException;
    if (se != null)
    {
        if (se.SocketErrorCode == SocketError.TimedOut)
        {
            ...
        }
    }
    else
    {
        ...
    }
}
 
Share this answer
 
Comments
aliwpf 12-Apr-17 2:11am    
thanks
Use Try ... Catch (Exception e) to catch all managed exceptions.
Or you could try to use an empty Try .. Catch, without anything after the Catch. This way you can catch unmanaged exceptions too.
When the code is unreachable for debugging, read this CodeProject article: System.Diagnostics Useful Actions[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900