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.
Related
I am pretty new to C#.
I am currently writing a WebSocket application, and I need to handle the NullReferenceException when the client disconnects, as I am constantly reading data from ClientSocket.
So the trouble is:
When I place the second try-catch block inside the first one, I am able to catch the NullReferenceException.
But when I remove the nested try-catch and try to catch the mentioned exception, it goes straight to the "finally" block.
try
{
using StreamReader streamReader = new StreamReader(stream);
while (true)
{
try
{
command = streamReader.ReadLine().Trim();
}
catch (NullReferenceException)
{
blah-blah
break;
}
}
}
//I place the NullReferenceException when removing the nested try-catch
catch (Exception e)
{
blah-blah
}
finally
{
blah-blah
}
You'll need to check exception type on the outer catch or simply throw NullReferenceException again from the first catch.
using (StreamReader streamReader = new StreamReader(stream))
{
while (true)
{
try
{
command = streamReader.ReadLine().Trim();
}
catch (NullReferenceException)
{
blah-blah
break;
}
}
}
more like your streamReader is null.
This question already has answers here:
Why does resharper say 'Catch clause with single 'throw' statement is redundant'?
(6 answers)
Closed 6 years ago.
Resharper thinks the last catch clause is redundant. Why?
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUrl);
try
{
var response = (HttpWebResponse) request.GetResponse();
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
var jsonResult = streamReader.ReadToEnd();
}
}
catch (WebException e)
{
Exception newEx;
if (e.Response != null)
{
using (var sr = new StreamReader(e.Response.GetResponseStream()))
{
newEx = new Exception(sr.ReadToEnd(), e);
}
}
else
{
newEx = new Exception(e.Message, e);
}
throw newEx;
}
catch (Exception ex) // Resharper thinks this clause is redundant
{
throw;
}
Because it is a default behavior - not caught exceptions will go further without need to rethrow them.
C# reference:
When an exception is thrown, the common language runtime (CLR) looks for the catch statement that handles this exception. If the currently executing method does not contain such a catch block, the CLR looks at the method that called the current method, and so on up the call stack.
In your particular case if you will not rethrow exceptions, other then WebException clr will continue to unwind stack looking for next try-catch.
If you rethrow that exceptions, clr will continue to unwind stack looking for next try-catch too.
So, no difference.
Probably because your catch block isn't doing anything except rethrowing the same exception:
catch (Exception ex) // Resharper thinks this clause is redundant
{
throw;
}
You could proof it by adding some code in that catch block.
I recently discussed with a coworker who told me that I was managing incorrently a stream into a try / catch / block. So I wanna know what would be a good approach for you.
try
{
StreamReader sr = new StreamReader("TestFile.txt");
//After that, here an operation of about 30 seconds to fulfill;
}
catch (IOException ioex)
{
throw new IOException("An error occurred while processing the file.", ioex);
}
catch (Exception ex)
{
throw new Exception("An generic error ocurred.");
}
finally
{
if(sr != null){
stream.Close();
stream = null;
}
}
He stated that having 2 Exception are unnecessary, even using the IOException. We can use only Exception. But the only thing that I want is to recognize where exactly the exception has been produced, because after opening the file, an operation of about 30 seconds will be performed.
So what would you think? We saw this MS example (http://msdn.microsoft.com/fr-Fr/library/system.io.streamreader.aspx) which it's simplier but in terms of performance or clean code, you find something strange?
Your opinions please!
-EDIT-----------------
Ok, I see the point but we were discussing about the Catch IOException and just using the Exception. In my opinion, like as in the example above you can know where the error ocurred; at the moment of managing the file or in the process after opening the file. That's my first question. And now, what do you think about this change below.
try
{
using(StreamReader sr = new StreamReader("TestFile.txt"))
{
//After that, here an operation of about 30 seconds to fulfill;
}
}
catch (Exception ex)
{
throw new Exception("An generic error ocurred.");
}
finally
{
if(sr != null){
stream.Close();
stream = null;
}
}
-------------------EDIT 2------------------------
Finally, I hope this would be my final solution. Thank you so much for your answers. So using is faster, efficient and just one exception is necessary.
try
{
using (StreamReader stream = sr = new StreamReader("TestFile.txt"))
{
//Operation
}
}
catch (Exception e)
{
throw new Exception(String.Format("An error ocurred while executing the data import: {0}", e.Message), e);
}
Any other comment would be appreciated!
you can use using block as below, and it will dispose the stream even on exception occurred
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
// do something with sr
}
Catch Exception if you're going to do something about. If you can't fix the problem, there's no point in catching it.
if you can't resolve the exception, it's best to just let the exception bubble up the exception and catch it there.
try
{
using(StreamReader sr = new StreamReader("TestFile.txt"))
{
// your code
}
}
catch (IOException ioex)
{
// do something to fix the problem
// log the exception
}
Don't catch an exception only to throw the same exception immediately, only now with less information and missing the stack frame of where the exception actually occurred.
If I came across something like
catch (Exception ex)
{
throw new Exception("An generic error ocurred.");
}
in a code review I would fail that review (not just for the grammar and spelling mistake either ;-)
At the very least, you should throw it with the original exception as an inner exception.
catch (Exception ex)
{
throw new Exception("A generic error occurred.", ex)
}
But to be perfectly frank, in this sample code it adds nothing whatsoever, it would be better removed entirely imo.
If you're rethrowing the exception instead of catching it, why bother creating a new exception? You're throwing away valuable information. There's literally no point in catching an exception only to throw it again. Nor is there any point replacing a helpful exception (as in, it's got all the diagnostic information anyone upstream might need) and replacing it with a generic exception.
For your situation, I'd simply:
using(var sr=new StreamReader())
{
//some code
}
all your other improvements are quite the opposite.
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.
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