简体   繁体   中英

How to handle the different type of exceptions from the same Exception Object?

For example Socket Exceptions can return either a timeout related message or an "actively refused" message which usually is caused by a closed port/port used for something else.

How would I properly do a switch case based on that?
I can just do an ex.Message.Contains() but if its run on a non-English system the message will not be English so the .Contains() will not match.
Is there some kind of signature I can check on or some kind of Exception Code that's global and doesn't change?

If you use try-catch properly, ie:

try
{
    ...
}
catch (SocketException ex) // this should have an s at the beginning...
{

}

You can use Visual Studio features to get this (write switch (ex.SocketErrorCode) and press tab ):

switch (ex.SocketErrorCode)
{
    case SocketError.AccessDenied:
        break;
    case SocketError.AddressAlreadyInUse:
        break;
    case SocketError.AddressFamilyNotSupported:
        break;
    case SocketError.AddressNotAvailable:
        break;
    case SocketError.AlreadyInProgress:
        break;
    case SocketError.ConnectionAborted:
        break;
    case SocketError.ConnectionRefused:
        break;
    case SocketError.ConnectionReset:
        break;
    // some dozens more
    default:
        break;
}

You can see the docs to find whichever cases you want to control.

Specifically for Socket Exceptions, you can get the socket error code through the SocketException.ErrorCode property, and switch on that. I like to use the enums posted here

But in a broader sense I think you are looking at it wrong. There is no "general" or "generic" way of handling exceptions with custom fields. Look at it from an inheritance point of view, the only fields you can count on are the ones inherited from Exception . If you are dealing with a class that inherits from Exception , then you should code specifically for that exception.

Keep in mind you can always use the type of exception for conditional handling:

try
{
...
}
catch(SocketException sockex)
{
...
}
catch(Exception ex)
{
...
}

You may separate the Socket Exception from any other exception, like this:

try
{
    // Your socket based code
}
catch (SocketException e) 
{
    // Handle Socket Exception
}
catch (Exception e) 
{
    // Handle Any other exception
}

Also you could check the HResult property to see if you can get different values depending on the kind of error type you're getting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM