In VS2019 community on Win10/64 I have a Com port with which my c# program exchanges serial data.
The same port can be opened by another application on the same computer.
When the port is opened by the other app and I try to access the port from my current app, I (expectedly) receive an exception message.
The exception message is of type: System.Reflection.TargetInvocationException: 'Exception has been thrown by the target of an invocation.
and the inner exception is: UnauthorizedAccessException: Access to the port 'COM6' is denied.
So far so good.
The problem is that I can not handle that (or any other relevant) exception. With any exception catch I still get the message and the program halts to be restarted.
I have tried the general exception handler and all relevant (as is indicated by the documentation) exceptions and placed a break in each handler, for no avail. The program still halts at the same exception message.
This is what I have tried (each with a break):
catch (Exception ex)
catch (System.Reflection.TargetInvocationException portInUse)
catch (UnauthorizedAccessException portInUse)
catch (InvalidOperationException portInUse)
catch (FormatException)
catch (System.ArgumentOutOfRangeException)
This is the full call stack message:
This exception was originally thrown at this call stack:
System.IO.Ports.InternalResources.WinIOError(int, string)
System.IO.Ports.SerialStream.SerialStream(string, int, System.IO.Ports.Parity, int,
System.IO.Ports.StopBits, int, int, System.IO.Ports.Handshake, bool, bool, bool, byte)
System.IO.Ports.SerialPort.Open()
Lift_Motor_Control.Main.btnSend_Click(object, System.EventArgs) in Main.cs
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Related
Is there any way to catch the connection exception thrown by the datastax cassandra driver for C#? It usually works fine, but the catch block does not execute when the remote host is down (that is, when a NoHostAvailableException is thrown). The debugger only halts and indicates the exception at Connect().
try
{
cluster = Cluster.Builder().AddContactPoint("<ip address>").Build();
session = (Session)cluster.Connect();
}
catch (NoHostAvailableException ex)
{
//Never executes
}
catch (Exception ex)
{
//Never executes
}
Found the fix, Visual Studio has a checkbox where you can choose whether or not you want to break on a certain exception (regardless of a try/catch), unchecking that solved everything.
I have a Console app that uses a parallel.foreach producing a number of working threads that performs some tasks such as
reading OS data through SNMP from a number of servers in our intranet and
writes these values to a SQL server DB.
When I ran the code within Visual Studio 2010 in either debug- or release mode the program executes without exceptions. When I deploy the program and run it outside VS I get an exception (.NET Runtime Exceptiopn).
Stack Trace:
Application: ServerMonitorSNMP.exe Framework Version: v4.0.30319 Description: The process was terminated due to an unhandled exception. Exception Info: System.AggregateException Stack: at System.Threading.Tasks.Parallel.ForWorker[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]](Int32, Int32, System.Threading.Tasks.ParallelOptions, System.Action`1,
...
at ServerMonitoringSNMP.Program.Main(System.String[])
The AggregateException details are:
System.UnhandledExceptionEventArgs
System.AggregateException: One or more errors occurred. ---> System.InvalidOperationException: Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.
...
(Inner Exception #0) System.InvalidOperationException: Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.
...
(Inner Exception #1) System.InvalidOperationException: Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.
...
(Inner Exception #2) System.InvalidOperationException: Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.
...
System.AggregateException: One or more errors occurred. ---> System.NullReferenceException: Object reference not set to an instance of an object.
at ServerMonitoringSNMP.Program.GetStorageValue(Dictionary`2 StorageQuery, Int32 diskOidIndex) in \Program.cs:line 896
This is an unhandled aggregate exception. You will need to catch this type of error, loop through its exceptions and log each one to figure out what is going on.
You are probably not breaking on these types of exceptions in your debug routine.
Turn on Break on All Exceptions (Debug, Exceptions) or (CTRL + ALT + E) and rerun the program.
This will show you the original exception when it was thrown in the first place.
Catch code:
catch (AggregateException e)
{
foreach (var ex in e.InnerExceptions)
{
//log here
}
}
The attached exception is too abstract. The best approach would be handle the TPL exception and log. Things shall be much clearer when you do so. Then you can updated the post with proper exception.
Eg:
try
{
YourSNMPTrapSenderMethod();
}
catch (AggregateException ae)
{
// This is where you can choose which exceptions to handle.
foreach (var ex in ae.InnerExceptions)
{
// log your exception. may be in temp directory
}
}
Or
try
{
YourSNMPTrapSenderMethod();
}
catch (AggregateException ex)
{
ex.Handle((x) =>
{
Log.Write(x);
return true;
});
}
static void YourSNMPTrapSenderMethod()
{
var exceptions = new ConcurrentQueue<Exception>();
Parallel.ForEach(data, d =>
{
try
{
//do your operations
}
catch (Exception e) { exceptions.Enqueue(e); }
});
if (exceptions.Count > 0) throw new AggregateException(exceptions);
}
I have a confusing problem and I could not any way to workaround it. I have a couple of lines of codes, and at some point, the Send function throws a System.Net.Sockets.SocketException. However, even though try has the catch block, it does not catches the exception and continue with normal flow. When I try to run the case where it needs to throw same exception, catch captures it pretty well.
Things I have tried:
Trying to change VS debugging settings 'Enable Only For My Code', but
it is already disabled.
I tried to both Debug and Release modes.
I tried using general Exception catcher, but none of them worked.
Here is the code, at some point, the connection from the server closes and the c Socket disconnects. It returns the System.Net.Sockets.SocketException, but below catch does not capture it.
try
{
// Some code here . . .
c.Send(clientData);
Print("Started uploading the file " + uploadFilename + ".");
upBox.Text = "";
Print("Finished uploading the file " + uploadFilename + ".");
}
catch (System.Net.Sockets.SocketException)
{
Print("You are disconnected from server!");
}
The reason you're not getting an exception ...
... is that no exception has occurred!
TCP/IP itself won't necessarily "notice" a disconnect ... unless you explicitly try to write to a closed socket.
Definitely check out Beej's Guide to Network Programming:
http://www.beej.us/guide/bgnet/.
See also:
http://stefan.buettcher.org/cs/conn_closed.html,
How to detect a TCP socket disconnection (with C Berkeley socket)
I'm learning netcode and multithreading in Monodevelop, using C# with GTK#. I've never done either before, and now I find myself needing to do both at once.
I've used a tutorial chat program that has no error handling, and I've caught an error that happens in the client every single time I disconnect from the server. The code that sits in a thread listening for messages is as follows, surrounded by try/catch statements:
try
{
while (Connected)
{
if (!srReceiver.EndOfStream && Connected)
{
string temp = srReceiver.ReadLine();
// Show the messages in the log TextBox
Gtk.Application.Invoke(delegate
{
UpdateLog(temp);
});
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
After which the function finishes and the thread ends.
The code that ends the connection looks like this, and runs on the main thread:
private void CloseConnection(string Reason)
{
// Show the reason why the connection is ending
UpdateLog(Reason);
// Enable and disable the appropriate controls on the form
txtIp.Sensitive = true;
txtUser.Sensitive = true;
txtMessage.Sensitive = false;
btnSend.Sensitive = false;
btnConnect.Label = "Connect";
// Close the objects
Connected = false;
swSender.Close();
srReceiver.Close();
tcpServer.Close();
}
And the try/catch statements above catch this error:
System.IO.IOException: Unable to read data from the transport
connection: A blocking operation was interrupted by a call to
WSACancelBlockingCall. ---> System.Net.Sockets.SocketException: A
blocking operation was interrupted by a call to WSACancelBlockingCall
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset,
Int32 size, SocketFlags socketFlags)
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32
offset, Int32 size)
--- End of inner exception stack trace ---
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32
offset, Int32 size)
at System.IO.StreamReader.ReadBuffer()
at System.IO.StreamReader.get_EndOfStream()
at ChatClientGTK.MainWindow.ReceiveMessages() in
g:\Android\Tutes\ChatClientRemake\ChatClientGTK\MainWindow.cs:line 157
Now, as far as I can tell, when srReciever.Close() happens in the main thread, srReciever.ReadLine() is still trying to execute in the listening thread, which is where the problem lies, but even when I comment out srReciever.Close(), I still get the error.
As far as I can tell, there are no side-effects caused by just catching the error and moving on, but that doesn't really sit right with me. Do I need to fix this error, and if so, does anyone have any ideas?
Instead of using a ReadLine, can't you just do a Read and build up the String until a CrLf is detected then output that to update log.
ReadLine is a blocking call meaning it will sit there and always error if the connection is closed.
Otherwise you could just ignore the error. I know what you mean when you say it doesn't sit right but unless anyone else can enlighten me, I don't see that there is any leak in resources due to it and if it is an expected error then you can handle it appropriately.
Also I would probably catch the specific exception
catch (IOException ex)
{
Console.WriteLine(ex.ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
The error is fine. If you really want it to go away, you can include a "bye" command in your protocol. So, if the server decides to disconnect, right before disconnecting he sends a "bye" to the client, so the client disconnects too, and most chances are that the exception will not be thrown. But you should still be prepared to catch it if it ever gets thrown. And then ignore it.
I'm constantly getting the following exception which is caused by a user initiating a download and it consequently failing (or being cancelled):
Error Message : The remote host closed
the connection. The error code is
0x80072746. Stack Trace : at
System.Web.Hosting.ISAPIWorkerRequestInProcForIIS6.FlushCore(Byte[]
status, Byte[] header, Int32
keepConnected, Int32 totalBodySize,
Int32 numBodyFragments, IntPtr[]
bodyFragments, Int32[]
bodyFragmentLengths, Int32
doneWithSession, Int32 finalStatus,
Boolean& async) at
System.Web.Hosting.ISAPIWorkerRequest.FlushCachedResponse(Boolean
isFinal) at
System.Web.Hosting.ISAPIWorkerRequest.FlushResponse(Boolean
finalFlush) at
I've searched all over the internet, and found an interesting article, however there doesn't seem to be a definitive answer as the best way to prevent this filling up the logs.
The user sees no error and there's no actual problem in the app as it occurs only (to my understanding) in situations out of its control (user cancelling download or loss of connection) but there has to be a way to prevent such an exception being reported.
I hate to say it but I'm tempted to check for this exception and empty catch block its ass away - but this makes me feel like a dirty programmer.
So - what is the accepted method of preventing this exception filling up my mailbox?
The error occurs when you try to send a response to the client but they have disconnected. You can verify this by setting a breakpoint on the Response.Redirect or wherever you are sending data to the client, wait for Visual Studio to hit the breakpoint, then cancel the request in IE (using the x in the location bar). This should cause the error to occur.
To capture the error you can use the following:
try
{
Response.Redirect("~/SomePage.aspx");
Response.End();
}
catch (System.Threading.ThreadAbortException)
{
// Do nothing. This will happen normally after the redirect.
}
catch (System.Web.HttpException ex)
{
if (ex.ErrorCode == unchecked((int)0x80070057)) //Error Code = -2147024809
{
// Do nothing. This will happen if browser closes connection.
}
else
{
throw ex;
}
}
Or in C# 6 you can use Exception filters to prevent having to re throw the error:
try
{
Response.Redirect("~/SomePage.aspx");
Response.End();
}
catch (System.Threading.ThreadAbortException)
{
// Do nothing. This will happen normally after the redirect.
}
catch (System.Web.HttpException ex) when (ex.ErrorCode == unchecked((int)0x80070057))
{
// Do nothing. This will happen if browser closes connection.
}
Which is a better debugging experience since it will stop on the statement throwing the exception with the current state and all local variables preserved instead of on the throw inside the catch block.
You cannot prevent a remote Host to close anything.
And in some protocols this is the normal (or at least accepted) way to say goodbye.
So you will have to handle this specific exception.
From a practical perspective, there is nothing wrong with cancelling a download by virtue of a dead computer or a killed web session, therefore catching remote host closed exceptions is perfectly acceptable.