Why is my exception handling code not handling exceptions? - c#

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.

Related

Webrequest cant "escape" timeout

Hi everyone im trying to create a method that will always return a url source, if for example internet goes off it will continue working until it comes up and return the url source and so on if something else occurs. So far in my method when i "turn off" the internet and "turn it on" back procedures continue normaly but im having an issue when a timeout occurs and im "falling" in a loop i know that the while(true) is not the right approach but im using it for my tests.
So how can i skip the timeout exception and "retry" my method?
public static async Task<string> GetUrlSource(string url)
{
string source = "";
while (true)
{
HttpWebRequest hwr = (HttpWebRequest)WebRequest.Create(url);
hwr.AllowAutoRedirect = true;
hwr.UserAgent = UserAgent;
hwr.Headers.Add(hd_ac_lang[0], hd_ac_lang[1]);
hwr.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
hwr.Timeout = 14000;
try
{
using (var response = hwr.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
source = await reader.ReadToEndAsync();
if (check_source(source))
{
return source;
}
}
}
}
catch (WebException ex)
{
hwr.Abort();
if (ex.Status == WebExceptionStatus.ProtocolError)
{
if (((HttpWebResponse)ex.Response).StatusCode == HttatusCode.NotFound)
{
// handle the 404 here
return "404";
}
}
else
{
Console.WriteLine(ex.Status.ToString());
}
}
}
}
Note: i used to have the hwr.Abort(); into a finnaly clause but it didnt help.
Edit: the console is writting this message every 14 seconds as my timeout i think its something related with that.
ِAn alternative solution to get rid of timeout problem can be is to use WebBrowser component and to navigate to the required url(webbrowser1.Navigate(url);) ,and to wait in a loop until the documentcompleted event is raised and then to get the source code by this line :
string source = webbrowser1.DocumentText;
Well it seems that i found a solution that was related with the service point of the request.
So in my catch when a timeout occurs im using this to release the connection.
hwr.ServicePoint.CloseConnectionGroup(hwr.ConnectionGroupName);
I'll keep this updated.

Windows service starts and then stops, can't figure out the bug [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I am trying to read a file at constant intervals and then send the data queried to a specific webserver. The following is the code I am using, but the service starts and stops without doing any thing. I can't Figure out the bug.
public partial class IPTProjectService : ServiceBase
{
private Thread checkingThread;
private System.Timers.Timer timer;
Boolean sendingTime;
public IPTProjectService()
{
InitializeComponent();
checkingThread = new Thread(update);
timer = new System.Timers.Timer(Properties.Settings.Default.TIMEINTERVAL);
timer.Elapsed += timer_Elapsed;
sendingTime = true;
}
void timer_Elapsed(object sender, ElapsedEventArgs e)
{
setSendingTime();
if (!File.Exists("Testfile.txt"))
{
File.Create("Testfile.txt");
timer_Elapsed(sender, e);
}
else
{
File.WriteAllText("Testfile.txt", timer.ToString());
}
}
private void setSendingTime()
{
sendingTime = true;
}
private void update()
{
while (true)
{
if (sendingTime)
{
CarpoolWebClient.sendData(Properties.Settings.Default.DATAFILE);
sendingTime = false;
}
}
}
protected override void OnStart(string[] args)
{
try
{
timer.Start();
checkingThread.Start();
}
catch (Exception ex)
{
Debug.Fail(ex.ToString());
}
}
protected override void OnStop()
{
try
{
timer.Stop();
checkingThread.Abort();
}
catch(Exception e)
{
StreamWriter writer = new StreamWriter("testfile.txt", true);
writer.Write(e.ToString());
writer.Close();
}
}
}
class CarpoolWebClient
{
public static void sendData(String fileName)
{
WebRequest req = null;
WebResponse rsp = null;
try
{
//URL of message broker
string uri = "http://localhost/IPTProject/receive_xml.php";
req = WebRequest.Create(uri);
req.Method = "POST";
req.ContentType = "text/xml";
// Wrap the request stream with a text-based writer
StreamWriter writer = new StreamWriter(req.GetRequestStream());
// Write the xml text into the stream
writer.WriteLine(GetTextFromXMLFile(#fileName));
writer.Close();
rsp = req.GetResponse();
}
catch (WebException webEx)
{
//MessageBox.Show(webEx.Message);
throw webEx;
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message);
throw ex;
}
finally
{
if (req != null) req.GetRequestStream().Close();
if (rsp != null) rsp.GetResponseStream().Close();
}
}
private static string GetTextFromXMLFile(string file)
{
StreamReader reader = new StreamReader(file);
string ret = reader.ReadToEnd();
reader.Close();
return ret;
}
}
If you can, debug the service. If it's a problem because the service is set to automatically start then you can use this "trick" to automatically attach the debugger and figure out what is going wrong that way.
The call to
File.Create("Testfile.txt");
timer_Elapsed(sender, e);
will create a file and return a FileStream to the newly created file. This file is subsequently still open then timer_Elapsed is called and will cause the application to fail as it cannot open the file a second time. See the MSDN Docs on the subject.
The Create call is not required for your code, you can simplyfying the method to the example below, and it should resolve this issue. Alternatively, close the FileStream object.
void timer_Elapsed(object sender, ElapsedEventArgs e)
{
setSendingTime();
File.WriteAllText("Testfile.txt", timer.ToString());
}
File.WriteAllText will create the file is it does not exist, and overwrite the file if it does exist, effectively doing the same thing as your check.
If this does not resolve the issue, check the event log for errors, or alternatively provided error handling code in your timer_Elapsed and update methods that log the error message.
As I was requesting the webserver on my own computer i.e. localhost, I didn't noticed that wampserver was not running. I checked the event log which showed me the WebException. Starting the wampserver code works fine. Thank you every one.
Yes, I encountered similar issues a lot of times...
Log all uncaught exceptions:
// Somewhere at the start of the constructor:
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
[...]
void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
// Log exeption e.ExceptionObject.ToString to a file
}
Also, I would use a try-catch + log in the update method to make sure that if the thread exits for any unknown reason, you find out the reason.
If these things don't work, it's usually something stupid like a missing DLL, the incorrect version of a DLL (64/32-bit mix), or something like that. This can be found in the event log.
That should do it :-)
If you are running this on a machine that has Visual Studio installed (e.g., your dev machine), add a call to
System.Diagnostics.Debugger.Launch();
in your startup or wherever appropriate. This will launch the Visual Studio debugger, so you don't have to fight with timing issues (Service stopping before you can manually attach the debugger)

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.

Compiler error in using block

I am trying to catch any errors that crop up when a URL is invalid, below is the original code:
public static void mymethod()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(firstline);
Stopwatch timer = new Stopwatch();
timer.Start();
using (var response = request.GetResponse())
timer.Stop();
timeTaken = timer.Elapsed.ToString();
}
I have tried to create an exception handler as below, but no luck:
public static void mymethod()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(firstline);
Stopwatch timer = new Stopwatch();
timer.Start();
try
{
using (var response = request.GetResponse())
}
catch
{
Console.WriteLine("error here...")
}
timer.Stop();
timeTaken = timer.Elapsed.ToString();
}
You should do something like this.
public static void ShowResponseAndTimeTaken(string firstline)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(firstline);
System.Diagnostics.Stopwatch timer = new Stopwatch();
timer.Start();
using (var response = request.GetResponse())
{
Console.WriteLine("Response : {0}", response);
}
timer.Stop();
Console.WriteLine("Time taken : {0}", timer.Elapsed);
}
catch(Exception e)
{
Console.WriteLine("error : {0}", e.Message);
}
}
Your usage of using-block is incorrect. The correct looks like this:
using (var response = request.GetResponse())
{
}
or just without the block:
var response = request.GetResponse();
response.Dispose()
I believe you cannot intercept it because it is thrown before "try" block:
it is possible that "firstline" variable contains a text with perhaps incorrectly formatted uri,
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(firstline);
You can also validate URL using regex instead of waiting for exception to be thrown - http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.aspx.
Here (http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.getresponse.aspx) you can find detailed description about GetResponse. Check what exceptions can be thrown and modify your current exception handling.
You shouldn't leave try...catch as it is. At least catch Exception class.
WebRequest.Create only throws if the scheme is invalid (the bit before the colon), there is a security error or if the URI you pass is null (although you have not enclosed that statement inside your try statement so such errors will be unhandled by the above code anyway).
To handle other errors, you should look at the HttpWebResponse.StatusCode property and handle the HTTP errors in way appropriate to your application.
I think you are talking about syntactic errors, because your code does not compile?
Try to add the missing semicolon on this line:
Console.WriteLine("error here...")
And the using-block contains no block:
using (var response = request.GetResponse())
remove the using:
var response = request.GetResponse())

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

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

Categories

Resources