chelocre chelocre - 1 month ago 10
C# Question

C# how to catch Exception

I am new in

C#
programming and I don't understand this problem.

using (WebClient wc = new WebClient())
{
try
{
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
HtmlResult = wc.UploadString(URI, myParameters);
}
catch(AuthenticateExeption a)
{
throw new AuthenticateExeption("I can not connect to the server...");
}
}


I am trying
catch
exeption using my
AuthenticateExeption
, but code never go to
throw new AuthenticateExeption("I can not connect to the server...");
and program always down on
HtmlResult = wc.UploadString(URI, myParameters);
line.

Why?

Answer

You are catching the Auth Exception and then you rethrow a new version of it...

Think more like this...

using (WebClient wc = new WebClient())
{   
   try
   {
        wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
        HtmlResult = wc.UploadString(URI, myParameters);
        if (some failed condition)
        {
           // I don't know what actually throws this, this is just for sim purposes
           throw new AuthenticateExeption("I can not connect");
        }
    }
    catch(AuthenticateExeption a)
    {
        // Handle the exception
        Log(a.Message) // etc....
    }
    catch(Exception e)
    {
        // Handle all other exceptions
    }
}

And from this point if you really wanted to throw the same exception you caught then you should first catch it, handle it, and then rethrow it for an external try/catch to furthermore handle.

Comments