I got an issue with a try catch block. It doesn't catch the exception of the code in the try block. Does anybody already had an issue like that and know how to solve it. The variable myCon is a MySqlConnection. The Exception occurs when the wait_timeout of the session is exceeded. Restarting, Rebuilt, change of CPU settings already tried.
P.S. When I press F10/F5 it doesn't jump into the catch block
I am not sure, but I can't see that Ping() is actually letting exceptions pass through. It just returns true or false.
For example the Open() method actually might throw an exception of type MySqlException, but not Ping()
It probably is the debug point made by Jon Skeet and Steven Wood, if not, have you tried removing HandleProcessCorruptedStateExceptions?
Related
I've recently run into this problem, and it doesn't make sense.
the following snippet is real:
try
{
File.Create(targetFile);
//File.WriteAllText(targetFile, $"test {DateTime.Now.ToString()}");
}
catch (UnauthorizedAccessException uaex)
{
}
I have checked it step by step, as soon as i get with the debugger to the "File.Create()" method, the exception rises, and it doesn't enter the catch block, also, if i remove the try-catch, it doesn't bubble up to the calling of the method which contains this.
Anyone got any idea why the try-catch and the bubbling doesn't work?
ps. The location where I am trying to create the file is write protected on purpose, this is just a way to check if it is.
I've made a mistake.
The exception is actually being caught, if you put anything in the catch block, it does execute.
To be fair the debugger confused me, by showing the exception pop-up right at the calling of the method, but that was solved by restarting the IDE
In other words, how are these two different?
try
{
// Something that can throw an error
}
catch
{
// Handle the error
}
finally
{
// Something that runs after the try statement
}
vs.
try
{
// Something that can throw an error
}
catch
{
// Handle the error
}
// Something that runs after the try statement
finally block always executes.
You can be sure, that this block will be executed no matter what.
Literally it is something like:
Try something, catch some exceptions(if told to and if they are there) and execute the
finally block finally.
If there is a break in the try block or an exception, it may cause the program to halt. In cases like these code that is mandarory to be executed, like closing open connections and returning items to the connection pools are writen in the finally block. The finally block ensures that the code written inside it will be executed.
If you only ever use general catches (i.e. catch without args or catch(Exception ex)), whether to put code in finally or after try/catch is basically a stylistic choice, as both a finally block and code after a try/catch will execute in any situation (barring deliberate escape mechanisms such as return).
However, if you use a narrow catch, and the exception isn't caught, what will happen is the finally block will still execute, however the code after the try/catch won't.
I am trying to export a Crystal ReportDocument using ExportToHttpResponse like so:
report.ExportToHttpResponse(exportOptions, HttpContext.Current.Response, true, "test");
When I first tried to run this, I received a System.Threading.ThreadAbortException. After reading about how this is a known error with ExportToHttpResponse in this question, I tried implementing the suggested workaround of wrapping the statement in a try/catch block like so:
try
{
report.ExportToHttpResponse(expOptions, HttpContext.Current.Response, true, "test");
}
catch (System.Threading.ThreadAbortException e)
{
}
As I understand it, this should catch and ignore the error, and proceed. However, I am still getting the System.Threading.ThreadAbortException on the closing bracket of the catch statement. My question is why is the exception still being received even though I am apparently catching it, and how could I go about fixing it so that the exception is ignored?
You can catch the ThreadAbortException and call the Thread.REsetAbort method, to cancel the bubbling of the exception.
However, keep in mind that response.end is a bad idea. Whenever you can try to call HttpApplication.CompleteRequest(), and read this SO question which proved really useful to me in this regard.
As far as I understand, using works like a try/catch/finally, so I would expect that if an exception occurs in a using statement it would get caught (which is kinda odd, because that would also mean that the exception is silently eaten). The using statement should catch the exception and call the Dispose method, however, that is not happening. I've devised a simple test to demonstrate the issue.
Here is where I force an exception to occur inside the using statement:
using (TcpClient client = new TcpClient())
{
// Why does this throw when the using statement is supposed to be a try/catch/finally?
client.Connect(null);
}
An exception is throw by client.Connect() (meaning that it was not caught by the using statement or that it was re-thrown):
System.ArgumentNullException: Value cannot be null.
Parameter name: remoteEP
at System.Net.Sockets.TcpClient.Connect(IPEndPoint remoteEP)
at DotNETSandbox.Program.Main(String[] args) in C:\path\to\Sandbox\Program.cs:line 42
According to a Microsoft article on the topic, the using statement might throw if the Dispose method throws.
However, when I'm following the using pattern, it is evident that the Dispose method does not throw:
TcpClient c2 = new TcpClient();
try
{
c2.Connect(null);
}
catch (Exception e)
{
// We caught the null ref exception
try
{
// Try to dispose: works fine, does not throw!
((IDisposable)c2).Dispose();
}
catch (Exception e2)
{
Console.WriteLine(e2.ToString());
}
Console.WriteLine(e.ToString());
}
I'm a little confused, since I was expecting using to behave like a try/catch. Could anybody explain why this is happening?
using is
try
{
}
finally
{
}
only !!!
there is no catch !
in .net you dont have to catch the exception..
its just a mechanism which calls DISPOSE method as soon as you leave the scope . thats all.
p.s. : " how will i know if my object can be used with using ?"
answer : don't worry - you will see error on compile time.
using is more of a try/finally without a catch.
Control can't leave the block without the object you're using being Disposed, that's it. Any exception thrown from inside the block will (after Disposing) be passed on as normal.
Edit: Picking nits on my own answer, in the special case of implementing an IEnumerable and yielding out of a using you could be said to leave the block without Dispose() being called, but when continuing the enumeration you'll end up right back inside again.
Because using doesn't behave like a try/catch/finally. It behaves like a try/finally.
Your first example, while it throws an Exception, will still properly Dispose the TcpClient.
Using statements behave like a try, finally block, not a try, catch, finally block.
Exceptions will still throw out of the using block.
As many people have said the using statement does not catch exceptions. But I can see your confusion from this article.
It says that IF the Dispose() fails it can hide any errors that were thrown within the using block.
Because the Dispose() occurs inside a "finally" block, the ApplicationException is never seen outside the using block if the Dispose() fails
I am trying to catch exceptions for my form client not being able to establish a connection to a server with this in the Connect callback:
try
{
client.EndConnect(async);
}
catch (Exception e)
{
client.Close();
return;
}
This works fine but this behavior is encapsulated in to a class so I want to call throw; instead of return; so that the client class can handle it instead, like so:
try
{
client.Connect(host, port);
}
catch
{
Console.WriteLine("Could not connect to: " + host + ":" + port.ToString());
}
So why not just call throw; then? Well, for some reason if I call throw;, throw new Exception();, or basically anything other than return; the program failsfast. I'm really not sure what's causing this. I tried removing client.Close(); to see if it was the problem but nothing. If I don't call return; the program just immediately exits with no error.
Anyone know what's going on here?
Edit: I do not understand why I am getting downvoted so much. I showed how I am attempting to catch these exceptions and am asking why they are not working properly. I think the problem may be (not sure, just came up with this) because within the asynchronous callback, because it is a new thread in the ThreadPool, calling throw; does not do anything because, because it is not synchronous, there is nothing to throw back to and the application dies. Even with this knowledge, I am not sure how to solve this problem unless I put some sort of try-catch on the entire program.
I suppose a solution could be just sticking with return; because there is nothing to throw back to (due to the asynchronous callback nature of the method) and instead raise an event indicating a failure of connection. Regardless, many thanks for the downvotes and helping me solve this problem. Oh wait...
What's happening is that the EndConnect is not happening on the same thread as your BeginConnect. When EndConnect throws an exception, it is caught by the worker thread's unhandled exception handler, which fails fast (the other option is that it gets ignored and you never find out that your code isn't working).
You have to come up with a way to tell your main form thread that the connect failed.
As others have pointed out, you'll need to catch your exception one way or another to avoid program termination.
For some ideas on how you can do that "globally", see How to catch ALL exceptions/crashes in a .NET app. Whether this is actually a good idea depends on the specific needs of your program...
Relevant for WinForms:
Can't tell based on your question alone, but in case this is actually a WinForms application, you may need to be cognizant of the difference in behavior of modal forms that throw exceptions, depending on whether the debugger is active or not. Let's say we have two forms - the second one is shown as a modal child of the first one:
If application was started through debugger, second form is closed and and stack unwinding goes all the way to the first form's catch block (if any).
If application is started outside debugger, stack unwinding stops before second form is closed and generic exception message is displayed. The second form stays open and catch block in the first form is never reached.