how to handle this ThreadAbort Exception..? - c#

i got this exception when i done the code given below..
"Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack."
--code--
try
{
if (retVal == 0)
Response.Redirect("Success.aspx");
}
catch(Exception error)
{
Response.Redirect("errorpage.aspx");
}
finally{
}
from searching in net i found it to be a bug and if its success then we should end response... ie " Response.Redirect("Success.aspx", false); ".it works fine.. is this a good method or there is any other efficient method to handle this exception please help....

Are you sure that it's an Exception? What type of exception is it?
It looks more like you have used 'Break' in the debugger and it cannot evaluate a watch or expression because it's busy running a line of code or non-managed call.
Try pressing F10 or F11 to step to the next line of managed code then looking at the expression again.
Using a breakpoint should also work.
If that doesn't solve it, please post a comment and I will try to respond or be more specific.
This is probably what you are seeing:
Also, Response.Redirect will always throw a ThreadAbortException, see here:
http://msdn.microsoft.com/en-us/library/a8wa7sdt(VS.80).aspx
To ensure that no more code gets executed, and the next code that will be run is in the context of generating the next page.
You could do this instead:
try
{
// code with Response.Redirect
}
catch (ThreadAbortException)
{
// ignore this exception, it is expected from Response.Redirect
}
catch (Exception ex)
{
// handle / log / redirect using ex
}
Hope that helps!

Related

UnauthorizedAccessException can't be caught

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

Using Response.Redirect(url) in Try / Catch Block

If my response to errors in a try/catch block is to redirect users to an error page, the try/catch block behaves as if there was an error when there was not. If I change it to do something else, the code works fine.
Example:
try
{
//do this SQL server stuff
}
catch
{
Response.Redirect(error.htm)
//Change this to lblErr.Text = "SQL ERROR"; and the code in try works fine.
}
From another post I learned there was a boolean overload to the Response.Redirect() method. I tried both true and false and the try/catch block still behaved as if there were an error.
What's the deal?
When you Response.Redirect, that throws a ThreadAbortException. So to get the outcome you are describing you'll want to mod your code as follows:
try
{
// Do some cool stuff that might break
}
catch(ThreadAbortException)
{
}
catch(Exception e)
{
// Catch other exceptions
Response.Redirect("~/myErrorPage.aspx");
}
Response.Redirect("url");
By design this will terminate the calling thread by throwing an exception.
Response.Redirect("url", false);
Will prevent the exception from being thrown, however will allow the code to continue executing.
Using
Response.Redirect("url", false);
HttpContext.Current.ApplicationInstance.CompleteRequest();
Will redirect the user and stop execution without throwing an exception.
You should use the HandleError attribute.
[HandleError]
public ActionResult Foo(){
//...
throw new Exception(); // or code that throws execptions
//...
}
That way exceptions automatically cause redirection to an error page.
You forgot the quotes and the semi-colon:
Response.Redirect("error.htm");

Is finally block in C# a must?

What is the difference between 2 conditions? Every time when method1 or method2 runs, there should be a code block that is required to run. It seems to me that 2 method are the same.
// example method1
void Method1(void)
{
try
{
// do something
}
catch (Exception ex)
{
// do something
}
finally
{
// do something whenever method1 runs
}
}
// example method2
void Method2(void)
{
try
{
// do something
}
catch (Exception ex)
{
// do something
}
// do something whenever method2 runs
}
Finally block seems to be unnecessary for me.
In your first example, you could re-throw the exception and the code inside the finally would still run. This would not be possible in the second example.
If you choose not to re-throw the exception, then yes there is little difference. However, this is considered bad form - very rarely should you need to consume an exception that you cannot explicitly handle.
It is a keyword to help you with code execution flow. When you throw an exception the execution flow of the code is affected (like using return), the finally keyword allows you to express that when an exception occurs (or you return from a try) you still want execution to do something as it's leaving.
To answer the question facetiously, it is a must when you need it and not when you don't.
Further Reading
To be on the safe side, before you attempt to start making use of this keyword, please read the documentation for it:
http://msdn.microsoft.com/en-us/library/zwc8s4fz.aspx
And the exception handling keywords in general:
http://msdn.microsoft.com/en-us/library/s7fekhdy.aspx
Examples
Catch an exception to do something with it, then re-throw it. Use finally to call any tidy-up code:
try
{
OpenConnectionToDatabase();
// something likely to fail
}
catch (Exception ex)
{
Log(ex);
throw;
// throw ex; // also works but behaves differently
}
// Not specifying an exception parameter also works, but you don't get exception details.
//catch (Exception)
//{
// Log("Something went wrong);
// throw;
//}
finally
{
CloseConnectionToDatabase();
}
Don't register any interest in catching exceptions, but use finally to tidy-up code:
try
{
OpenConnectionToDatabase();
// something likely to fail
}
finally
{
CloseConnectionToDatabase();
}
Return from your try because it looks nicely formatted, but still use finally to tidy-up code:
try
{
OpenConnectionToDatabase();
return 42;
}
finally
{
CloseConnectionToDatabase();
}
As you know the code written inside the finally block always runs.
Please have a look onto the following point written below, it will clear your all confusion.
Finally is used for Resource management. Mainly for releasing an resources. It always runs independent upon the Exception.
As we know catch is used for handle an exception, but sometimes it fails to handle to an External exception. Then the finally block is used to handle that exception to perform the operation.
The code in the finally block will run anyway after the try-catch, it is very usefull for clean up.
try
{
// open resources
}
catch (Exception ex)
{
// something bad happened
}
finally
{
// close resources that are still opened
}
This will behave very differently depending on whether you return from the try, for example. Also - the finally will run even if the catch throws an exception (or re-throws the original exception), which will not happen without the finally.
So: it isn't required, but it will behave differently. So if you want the code to happen, put it in the finally.
In many ways, try/finally is much more common than try/catch or try/catch/finally.
You do not absolutely have to have the finally block, however, having it guarantees that the code within it will always run (unless there is an exception in the finally!).
Consider the following:
void Method2(void)
{
try
{
// do something
}
catch (Exception ex)
{
// do something
throw;
}
// do something whenever method2 runs
}
the code after the try/catch will not execute if an exception is thrown. Additionally, if the code within the catch block has an error that causes an exception (such as your logging throwing an unexpected exception) the code that should have been in the finally will not run, leaving and cleanup undone.
Also a return statement will cause that code to not be run, while the finally will still be executed (also, here you can see that the catch can be skipped too, allowing any exceptions to propogate upwards - AFTER executing the finally):
void Method2(void)
{
try
{
// do something
return
}
finally
{
// do something whenever method2 runs
}
}
Whenever you have cleanup code that must be run at the end of a method, use finally (or if your objects implement IDisposable use the using statement).
The finally block ensures that any code within it ALWAYS gets executed so if you have a return statement inside your try block or rethrow an exception within your catch block, the code inside the finally block will always execute.
It is a must if you need to ensure that something happens regardless (e.g. disposing of a resource etc)
The big difference is that try...catch will swallow the exception, hiding the fact that an error occurred. try..finally will run your cleanup code and then the exception will keep going, to be handled by something that knows what to do with it.

How to handle an exception correctly

I have an xmlbuilder utility class which calls a couple of methods to build an xml file
public XMLBuilder(String searchVal)
{
this.searchVal = searchVal;
try
{
getData();
returnedData = processDataInToOriginalFormat();
WriteBasicTemplate();
}
catch (WebException)
{
//If this is thrown then there was an error processing the HTTP request for MSO data.
//In this case then i should avoid writing the xml for concordance.
serviceAvailable = false;
MessageBox.Show("Could not connect to the required Service.");
}
catch (NoDataFoundException ndfe)
{
//propegate this back up the chain to the calling class
throw;
}
processDataInToOriginalFormat(); this is a method in a class which causes an exception if the service is not available and i have propagated the exception back to here to deal with. I was going to try and set a boolean flag to indicate whether to write a certain bit of xml. If the flag is false then dont write it.
I forgot however that exceptions stop programme flow and now i realise this isnt possible as if an exception occurs the rest of the code doesn't resume. how can i get around this? just add the WriteBasicTemplate(); call in to my catch clause?
Thanks
The logic of your code is somewhat confusing and as it's not obvious what "serviceAvailable = false" will do, it's hard to give detailed tips. The general rule of excetion handling is, to catch (and not rethrow) them, if you really know what to do with them and how to fix the problem. I you don't know that or the program will be in a state where it cannot continue working, let the exception go through and let your program crash.
In your case I might structure the code like this:
try
{
returnedData = processDataInToOriginalFormat();
// put code here which should only be executed in
// case of no exception
}
catch (WebException)
{
// do what ever is required to handel the problem
MessageBox.Show("Could not connect to the required Service.");
}
// code which should be executed in every case
WriteBasicTemplate();
You shoudl also look at the "finally"-block. Depending on your requirements, you should WriteBasicTemplate in such a block. But I would probably not do so in your case. It's rather used for resource cleanup or something like that.

Exception Handling - line skipped and sqle is null

IDE = VS7 or 2002
Hi all, I have a really weird problem here. The code doesn't appear to be executing as expected. I'm running this through the debugger and it's performing really strangely.
I have made sure that the Virtual Directory is using ASP.NET 1.0.3705.
The code follows and I explain what the debugger shows me as the execution steps in the comments:
try
{
objConnection.Open(); // STARTS HERE
objCommand.ExecuteNonQuery(); // DOES NOT THROW EXCEPTION
int c = 0; // THIS LINE IS EXECUTED
}
catch (SqlException sqle)
{
LogError(); // THIS LINE IS NOT EXECUTED
throw sqle; // THIS LINE IS EXECUTED AFTER THE int c = 0;
// sqle IS NULL
// EXCEPTION IS NOT CAUGHT AND
// EXECUTION CONTINUES IN FINALLY BLOCK
}
finally
{
// EXECUTES AS EXPECTED FROM HERE ON OUT,
// AS THOUGH THE throw sqle; DID NOT HAPPEN.
if (objConnection.State == ConnectionState.Open) objConnection.Close();
}
Has anyone experienced this strange behaviour before? Any idea how to fix it? I may change the method extensively, but I'd still like to know why this is happening.
I suspect since the sqle is null that is why the throw does not behave as expected. But why did we jump into this code block in the first place?
I have reloaded it several times, saved and rebuilt, and executed with the debugger and watched this behaviour multiple times.
Thank you all for your help!
All the best,
Graham
Very strange. I'm not sure what's going on with your code, but one thing I saw is the use of:
catch (SqlException sqle)
{
LogError(); // THIS LINE IS NOT EXECUTED
throw sqle; // THIS LINE IS EXECUTED AFTER THE int c = 0;
// sqle IS NULL
// EXCEPTION IS NOT CAUGHT AND
// EXECUTION CONTINUES IN FINALLY BLOCK
}
You want to write:
catch (SqlException sqle)
{
LogError();
throw;
}
To re-throw the exception.
Wait.. your code doesn't throw an exception and you're wondering why it doesn't execute the catch block?
EDIT (referencing your comment):
That sounds really hard to believe. I never heard of a case where the actual exception inside the catch block was null and as you already mentioned did the first line inside the catch block not execute which in my opinion points into the direction that there was no exception at all.
Did you try to check the program flow by using old-fashioned debugging techniques (Debug.WriteLine) and skipping the debugger?
My assumption is that you're looking at the wrong place where the exception is thrown.. or there's no exception at all.

Categories

Resources