.NET exception doesn't get passed from class to main program - c#

I created a simple console application using C#. It creates an instance of a class and calls one of the class' methods. This method contains a try-catch block to catch exceptions of the type System.Net.WebException and rethrow it so that the main method can catch it and act appropriately. When I execute the compiled application the exception does not get passed to the main class and the user would never see my custom error message. Instead this screen pops up telling me that there was an unhandled WebException (it's in German but I think it can be recognized anyway ;-)):
alt text http://img29.imageshack.us/img29/4581/crapq.png
This is the method inside my class named BuffaloRouter:
public void Login()
{
string sUrl = _sUrl + "/somestuff.htm";
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(sUrl);
CredentialCache credCache = new CredentialCache();
credCache.Add(new Uri(sUrl), "Basic", _credential);
request.Credentials = credCache;
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream receiveStream = response.GetResponseStream();
StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
_sContent = reader.ReadToEnd();
response.Close();
receiveStream.Dispose();
reader.Dispose();
_parseSessionIds();
}
catch (WebException)
{
throw;
}
}
And this is the method inside my main class:
private static bool _login()
{
_router = new BuffaloRouter(_sIP, new System.Net.NetworkCredential("root", _sPassword));
try
{
Console.WriteLine("Login...");
_router.Login();
return true;
}
catch (System.Net.WebException)
{
_showErrorMessage("Could not connect to " + _sIP);
return false;
}
}
UPDATE:
I feel more than a little embarrassed and would rather not talk about it. But like a few times before I didn't relly look at what I was doing ;-)
The method inside the main class was not even invoked when I was running the app. The one that was invoked didn't have a try-catch block so that the exception thrown inside my class' method made the app do what it was supposed to, i.e. CRASH!!
I'm stupid, sorry for wasting everone's time.

If all you're doing is rethrowing the exception, then you don't need to catch it in the first place. Just remove the try...catch from your Login method.
Having done that temporarily edit your code to catch the general exception and debug it to find out what exception is actually being raised. Having done that edit the code again to catch that exception (and that exception alone).

As ChrisF has indicated you don't need to rethrow the error in the Login method. If your catch block is not running in the _login method, then I would guess your not catching the right exception.
Are you positive your getting a System.Net.WebException

Related

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?
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.
You may be getting another type of exception. If you replace catch(AuthenticationException a) with catch(Exception ex) and add a breakpoint on that line then you can watch ex to see what type of exception is occurring.
Alternatively, since .Net will catch the most specific exception (i.e. most-derived type) first, so you could leave your current catch block and add an additional catch(Exception ex) block underneath it so that if an AuthenticateException occurs it will get caught, but all other exceptions will drop through to the more general case.

c# application is crashing when the server is down

I'm using this code, to fetch the latest version of my app in *Form1_Load*:
string result1 = null;
string url1 = "http://site.com/version.html";
WebResponse response1 = null;
StreamReader reader1 = null;
try
{
HttpWebRequest request1 = (HttpWebRequest)WebRequest.Create(url1);
request1.Method = "GET";
response1 = request1.GetResponse();
reader1 = new StreamReader(response1.GetResponseStream(), Encoding.UTF8);
result1 = reader1.ReadToEnd();
}
catch (Exception ex)
{
// show the error if any.
}
finally
{
if (reader1 != null)
reader1.Close();
if (response1 != null)
response1.Close();
}
The problem is that when I shut the server down the whole application is stucking and a window is popping out,saying:
Unable to connect to the remote server
Which seems legit.
Is there a way to bypass this crash (when the server is down) and break out of the version checking?
Add an additional catch block that catches the specific Exception type that you're seeing... the code will look like...
try
{
//*yadda yadda yadda*
}
catch (System.Net.WebException WebEx)
{
//*Correctly set up a situation where the rest of your program will know there was a connection problem to the website.*
}
catch (Exception ex)
{
//*Do the error catching you do now*
}
finally
{
//*yadda yadda*
}
This construction will allow you to handle WebExceptions differently from other kinds of exceptions: note that all Exceptions derive from one base class, Exception, and you can make your own for uses like this.

Properties of Inner Exception are Disposed?

I am writing a unit test for a WCF web service. I am deliberately sending an invalid request to the server which throws a WebExceptionFault<string>. In the unit test, the Exception that gets caught is an EndpointNotFoundException with the standard WebException in the InnerException property. I want to verify the body of the response matches the string that I think should be there.
I am coming accross a problem, however, as the Response property of the WebException (which is a System.Net.SyncMemoryStream) is Disposed and can not be read.
My code:
Clubs actual;
try
{
//"201" is an invalid argument for the first parameter
actual = new Clubs(channel.GetClubs("201", "123"));
}
catch (EndpointNotFoundException e)
{
WebException w = e.InnerException as WebException;
Assert.IsNotNull(w);
HttpWebResponse resp = w.Response as HttpWebResponse;
Assert.IsNotNull(resp);
Assert.AreEqual(resp.StatusCode, HttpStatusCode.NotFound);
//Next line throws an ArgumentException saying Stream not readable
//Investigation shows it has been disposed
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
Assert.AreEqual(sr.ReadToEnd(), "League not allowed for selected club");
}
Is it normal that the properties of the InnerException are disposed? Is there any way around this?
Seems a Exception serialization issue. You might have to trap the error on server and custom build a error message
How to serialize an Exception object in C#?

Order of execution of try catch and finally block

I am confused about the order of try, catch and finally block execution.
I also want to know when should I use try-catch block and what should I put in the try-catch block?
I also want to know if some exception comes in try block then if an action is taken corresponding to try block then which one is executed first catch or finally (which is always to be executed)?
After the execution of these two does control return to try block or it leave it?
If you have (note: this is not valid C#, see below for a valid example):
try {
// ... some code: A
} catch(...) {
// ... exception code: B
} finally {
// finally code: C
}
Code A is going to be executed. If all goes well (i.e. no exceptions get thrown while A is executing), it is going to go to finally, so code C is going to be executed. If an exception is thrown while A is executed, then it will go to B and then finally to C.
As an example, here's a valid C# code block from http://msdn.microsoft.com/en-us/library/dszsf989.aspx:
public class EHClass
{
void ReadFile(int index)
{
// To run this code, substitute a valid path from your local machine
string path = #"c:\users\public\test.txt";
System.IO.StreamReader file = new System.IO.StreamReader(path);
char[] buffer = new char[10];
try
{
file.ReadBlock(buffer, index, buffer.Length);
}
catch (System.IO.IOException e)
{
Console.WriteLine("Error reading from {0}. Message = {1}", path, e.Message);
}
finally
{
if (file != null)
{
file.Close();
}
}
// Do something with buffer...
}
}
The reason to use try/catch/finally is to prevent your program to fail if there is an error in some code (A in the above example). If there is a problem, you can use catch part to catch the problem and do something useful, such as inform the user, log the exception to a log file, try again or try something different that you suppose might work instead of what you tried originally.
finally is used to ensure that some cleanup is performed. E.g. in A you might try to open a file and read it. If opening succeeds, but read fails, you will have an open file dangling. What you would like in that case is to have it closed, which you would do in finally block - this block always gets executed, guaranteeing the closing of the file.
Take a look here for more info:
http://msdn.microsoft.com/en-us/library/0yd65esw.aspx
http://www.c-sharpcorner.com/UploadFile/puranindia/75/Default.aspx
A try ... catch block is used to catch exceptions. In the try block you put the code that you expect may raise an exception.
If no exception occurs then the code in the try block completes as expected. If there's a finally block then that will execute next.
If an exception does occur then execution jumps to the start of the first matching catch block. Once that code is complete the finally block (if it exists) is executed. Execution does not return to the try block.
You should almost never use try/catch.
You should only catch exceptions that you can actually correct, and only when you're expecting them. Otherwise, let the caller handle the exception - or not.
If used, any catch clauses are executed first - only one of them.
Then, finally is "finally" executed.
This has been stated better in many places, but I'll try. The following code:
try
{
// Do something here
}
catch (Exception ex)
{
MessageBox.Show("Friendly error message");
}
does not fix the exception. It hides the exception so that the problem will never be fixed. That code has no idea which exception was thrown, because it will catch all of them, and it does nothing to correct the problem - it just tells the user a polite fiction.
The fact of the matter is that the code above should be replaced with the following:
// Do something here
This way, if the caller of this method knows how to fix particular problems, then the caller can fix them. You will not have removed that option from the caller.
If the caller does not know how to fix the problem, then the caller should also not catch the exception.
Here is an example (from MSDN) of using exceptions in a reasonable manner. It's a modified form of the example in the documentation of the SmtpFailedRecipientsException Class.
public static void RetryIfBusy(string server)
{
MailAddress from = new MailAddress("ben#contoso.com");
MailAddress to = new MailAddress("jane#contoso.com");
using (
MailMessage message = new MailMessage(from, to)
{
Subject = "Using the SmtpClient class.",
Body =
#"Using this feature, you can send an e-mail message from an application very easily."
})
{
message.CC.Add(new MailAddress("Notifications#contoso.com"));
using (SmtpClient client = new SmtpClient(server) {Credentials = CredentialCache.DefaultNetworkCredentials})
{
Console.WriteLine("Sending an e-mail message to {0} using the SMTP host {1}.", to.Address, client.Host);
try
{
client.Send(message);
}
catch (SmtpFailedRecipientsException ex)
{
foreach (var t in ex.InnerExceptions)
{
var status = t.StatusCode;
if (status == SmtpStatusCode.MailboxBusy || status == SmtpStatusCode.MailboxUnavailable)
{
Console.WriteLine("Delivery failed - retrying in 5 seconds.");
System.Threading.Thread.Sleep(5000); // Use better retry logic than this!
client.Send(message);
}
else
{
Console.WriteLine("Failed to deliver message to {0}", t.FailedRecipient);
// Do something better to log the exception
}
}
}
catch (SmtpException ex)
{
// Here, if you know what to do about particular SMTP status codes,
// you can look in ex.StatusCode to decide how to handle this exception
// Otherwise, in here, you at least know there was an email problem
}
// Note that no other, less specific exceptions are caught here, since we don't know
// what do do about them
}
}
}
Note that this code uses try/catch to surround a small piece of code. Within that try/catch block, if an SmtpException or SmtpFailedRecipientsException is thrown, we know what to do about it. If, for instance, we were to catch IOException, we would not know what it meant, or what to do about it. Any exception you don't actually know how to correct should not be caught, except maybe to add information to the exception, log it, and rethrow.
Here is an example:
try
{
someFunctionThatWorks();
functionThatThrowsAnException(); // As soon as this function throws an exception we are taken to the catch block
anotherFunction(); // <-- This line will never get executed
}
catch(Exception e)
{
// Here you can handle the exception, if you don't know how to handle it you should not be catching it
// After this you will not be taken back to the try block, you will go right to the finally block
}
finally
{
// Code here is always executed at the very end, regardless of whether an exception was thrown or not
}
I'd like to elaborate a bit on this and extend #icyrock.com answer with scenario when you rethrow the exception in the catch block so it is handled lower on the execution stack...
I gave it a try with the following code:
static void Main(string[] args)
{
try
{
// pick one:
// NormalExcecution();
// TroubleExcecution();
}
catch
{
Console.WriteLine("block D");
}
Console.ReadKey();
}
private static void NormalExcecution()
{
try
{
Console.WriteLine("block A");
}
catch (Exception)
{
Console.WriteLine("block B");
throw;
}
finally
{
Console.WriteLine("block C");
}
}
private static void TroubleExcecution()
{
try
{
Console.WriteLine("block A");
throw new Exception();
}
catch (Exception)
{
Console.WriteLine("block B");
throw;
}
finally
{
Console.WriteLine("block C");
}
}
So when there is no exception in block A, then the sequence is as follows (exception handling blocks are never hit):
Block A
Block C
When there's some problem with block A, the sequence is as follows:
block A
block B
block C
block D
Another words, the occurring exception is first handled by block B, then the finally clause is executed, only after that the exception is rethrown and handled lower on the execution stack (block D).
Please mind I may be wrong with what is actually going on under the hood of the .NET framework - I just present the results I observed :)

Why is my exception handling code not handling exceptions?

I have some C# code that pulls down a remote website using the HttpWebRequest class. I'm handling errors with a try/catch, but some errors (like Webrequest and IOException) don't seem to be getting "caught" with the way I have it setup:
try
{
StartScrap("http://www.domain.com");
}
catch (Exception ex)
{
LogError(ex.ToString();
}
private void StartScrap(string url)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
string responseText = String.Empty;
using (StreamReader readerStream = new StreamReader(responseStream, System.Text.Encoding.UTF8))
{
responseText = readerStream.ReadToEnd(); <-- I will sometimes get a Webexception error here that won't get caught above and stops the code
}
}
}
Update: There is more to the code, so maybe it is something outside of the code I posted? I am basically using this code in a Windows Application on a form that has a NotifyIcon. I'm using the Timer class to run the code at a certain timer interval. This is how I have it setup:
public TrayIcon()
{
InitializeComponent();
}
private void TrayIcon_Load(object sender, EventArgs e)
{
try
{
StartScrap("http://www.domain.com");
}
catch (Exception ex)
{
LogError(ex.ToString());
}
finally
{
StartTimer();
}
}
private void StartTimer()
{
Timer Clock = new Timer();
Clock.Interval = 600000;
Clock.Start();
Clock.Tick += new EventHandler(TrayIcon_Load);
}
What exactly do you mean by "stops the code"? Are you running in a debugger by any chance? My guess is that if you run outside the debugger - or just hit "run" again in the debugger - you'll get into the catch block with no problems. Alternatively, go into the debugger settings and change at which point the debugger steps in.
Of course, if this isn't happening in the debugger, we just need more information about exactly what you're seeing.
Could it be that LogError is throwing an exception?
Frankly speaking I am not sure what exactly happening but I will suggest you to go with ELMAH.(Error Logging Modules and Handlers)
Here is a step by step How to for ELMAH.
Nevermind, I found out I was calling the wrong function my Timer class and it was bypassing the event handler.

Categories

Resources