how to differentiate among different exceptions of same class?

418 Views Asked by At

how to check whether its is login info exception or a connection lost exception if the the exceptions are form the same class?

private bool checkFileExists(string absoluteRemoteLocation)
{
      try
      {
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(absoluteRemoteLocation);
            request.Method = WebRequestMethods.Ftp.UploadFile;
            request.Timeout = timeOut;
            request.Credentials = new NetworkCredential(this.username, this.password);
            request.GetResponse();
            return true;
      }
      catch(Exception e) //i want to check here
      {
            var g = e.ToString();
            return false;
      }
}
4

There are 4 best solutions below

0
Salah Akbari On

Use different catch block like this:

catch (System.TimeoutException e)
{
    var g = e.ToString();
    return false;
}

catch (System.Net.WebException e)
{
    var g = e.ToString();
    return false;
}
0
chaudharyp On

Use is keyword of C#.

<!-- language: C# -->
catch (Exception e) {
    if (e is LoginInfoException) // do something
    else if (e is ConnectionLostException) // do something else
}

For reference, check this link.

4
blogbydev On

Isn't this what you want?

public class Program
{    
    public static void Main(string[] args)
    {
        try
        {           
                throw new ConnectionLostException();
        }
        catch (Exception ex)
        {

            if (ex is LoginInfoException)
            {
                Console.WriteLine ("LoginInfoException");
            }
            else if (ex is ConnectionLostException)
            {
                Console.WriteLine ("ConnectionLostException");  
            }
        }
    }
}

public class LoginInfoException : WebException
{
   public String Message { get; set; }

}

public class ConnectionLostException : WebException
{
   public String Message { get; set; }
}
0
D. Ben Knoble On

This is a simple example of a filter that will catch different exceptions. I don't know much about the hierarchy of exceptions you're dealing with, but this will allow you to filter what exceptions get caught where.

public class CatchExceptions
{
    public void SomeMethod ()
    {
        try
        {
            //some stuff that throws exceptions
        }
        catch (WebException e) if (e is LoginInfoException)
        {}
        catch (WebException e) if (e is ConnectionLostException)
        {}
    }
}

Obviously you'll have to figure out what you can use to filter the exceptions like so; it appears that the two examples I used above are not concrete types. You may need to do some restructuring to figure out how to differentiate between the two.