Can a try/catch block prevent an error from occuring? - c#

I have some code in my application that throws an error every so often (System.AccessViolationException) - So I wrapped it in a try/catch block and set a debug point and logging method in the catch element. I've found that since I did this the error has stopped happening - the debug point is never hit and nothing is logged. As soon as I remove the try from around the code I get the error again. What could be causing this?
The code is pretty trivial:
try
{
var f1 = new ResizeNearestNeighbor(lfu.Width, lfu.Height);
var f2 = new Crop(ViewRectangle);
lfu = f2.Apply(lfu);
lfu = f1.Apply(lfu);
}
catch (Exception ex)
{
MainForm.LogExceptionToFile(ex);//never hit
}

There could be a couple of options:
or MainForm.LogExceptionToFile(ex); does not work as it expected
or, if we are 100% sure in that method, probably injecting try/catch block introduces in the code flow that microscopic delay (due the more IL code to execute/control), which is necessary to not get AccessViolationException on that machine. Which means, that is absolutely possible that you will get that exception on some other machine.

A AccessViolation Exception can't be skipped or catched.
Every time this exception happens it would be thrown!

Related

Code in filtered exception handler throws NullReferenceException when accessing exception

When I compile a UWP app with the .NET Native compiler and turn on code optimizations (essentially release mode), then I get a NullReferenceException when I try to access the actual exception in the catch block.
Code Sample:
try
{
throw new ArgumentNullException("Param");
}
catch (ArgumentNullException ex) when (ex.ParamName == "Param")
{
ErrorBlock.Text = ex.ParamName; // ErrorBlock is a TextBlock in the xaml
}
catch (Exception)
{
}
It goes into the correct catch block, and throws a NullReferenceException when I access ex. This only fails if both .Net Native and code optimizations are on.
What causes this issue?
I am not exactly sure why it is going wrong (have been debugging for quite some time now), but the lack of await made me curious.
If you do await the ShowAsync method the code runs without a problem (obviously you need to make the method async if you didn't do that yet):
await new MessageDialog("Argument null exception: " + argEx.Message).ShowAsync();
While the code block without the await failed. Not sure if this is a bug or something you should have fixed...
I work on the .NET Native runtime and compiler team.
This is a bug inside of our compiler. You can think of each exception handling region (try, catch, finally, when) as a small function or "funclet". We lose track of the exception object when setting up the stack for the "when" (aka filter block). This bug is corrected in Windows Tools 1.3 which, given no major setbacks, should be shipping in another week or two. It'll show up as an update for folks that have installed VS 2015 Update 2.
Let me know if you have any other questions.

Can I get some clarification on the try catch finally concept? (C#) [duplicate]

In a Try Catch Finally block, does the finally block always execute no matter what, or only if the catch block does not return an error?
I was under the impression that the finally block only executes if the catch block passes without errors. If the catch block is executed because of an error, shouldn't it stop execution all together and return the error message if any?
The finally block (nearly) always executes, whether or not there was an exception.
I say nearly because there are a few cases where finally isn't guaranteed to be called:
If there is an infinite loop or deadlock in your code so that the execution remains inside the try or catch blocks then the finally block will never execute.
If your application is terminated abruptly by killing the process.
Power cut.
Calling Environment.FailFast.
Some exceptions such as:
StackOverflowException
OutOfMemoryException
ExecutingEngineException (now obsolete)
An exception thrown in a finalizer (source).
Furthermore, even if the finally block is entered if a ThreadAbortException occurs just as the thread enters the finally block the code in the finally block will not be run.
There may be some other cases too...
Not only will a finally block execute following a catch block, try does not even require that any exception be caught for the finally to execute. The following is perfectly legal code:
try
{
//do stuff
}
finally
{
//clean up
}
I actually took out the catch blocks in some code I inherited when the catch block consisted of:
catch(Exception ex)
{
throw ex;
}
In that case, all that was required was to clean up, so I left it with just a try{} and finally{} block and let exceptions bubble up with their stack trace intact.
the finally block executes in almost every case. That's why it's called 'finally'.
For an example, see this article on c-sharpcorner.com.
Update: It's true, if you plug the cable, melt the processor or grind the motherboard, even the most final 'finally' will not be executed.
But in almost every 'normal' scenario, i.e. wether your code throws an exception or not, the finally block will be executed. To my knowledge the only 'real' exception to this rule is a stackoverflow exception which will terminate the program w/o entering finally.
Update 2: This question was asked specifically for C#. This answer is NOT covering Java, Python, Matlab or Scheme.
The finally block will execute, but you'll need to be careful of exceptions within the finally block.
try {
// some disposable method "o"
} finally {
o.Dispose(); // if o is null, exception is thrown
// anything after this exception will fail to execute
}
The code inside the finally block gets always executed, regadless if there was an exception. By the way, I think there are already numerous threads on SO that deal with this question.

in C# is it possible to force control to pass through a finally block if an exception is thrown by an associated catch block?

I know that in Java, if an exception is caught by a catch clause and its catch block throws an exception, control would pass throw the associated finally block (if any) before the thread is terminated. This does not appear to be the case in C#, however.
It is possible to almost mirror this behavior in C# is by putting a try-finally statement inside the try block of the try-catch statement with the catch block that throws the exception, but that would be a problem if, for example, the finally block is supposed to contain code that disposes a Stream Writer that is supposed to log the exception.
Is there a clean way to achieve java-like try-catch-finally exception handling behavior in C#?
Here's an update with the requested sample code:
StreamWriter writer = new StreamWriter("C:\\log.txt");
try
{
throw new Exception();
}
catch (Exception e)
{
writer.WriteLine(e.Message);
throw e;
}
finally
{
if (writer != null)
{
writer.Dispose();
}
}
Add that code to a console application, run it, let the re-thrown exception go unhandled, attempt to delete C:\log.txt. You won't be able to, because control never passed through the finally block. Also, if you add a breakpoint to some line inside the finally block you will see that it doesn't get hit. (I'm using VS2005).
As far as I know, the only way to force control to pass through the finally block is if the re-thrown exception is handled by the catch block of an enclosing try block (if you took the code above and placed it inside the try block of another try-catch statement).
If the exception is not caught and is allowed to terminate the application, as in the sample code I provided, control won't pass through the finally block.
In Java it would. In C#, at least based on what I have seen, it would not.
No, this is incorrect. C# will always execute the finally block, even after an exception is thrown/re-thrown from the catch block. See When is finally run if you throw an exception from the catch block?.
In the .NET Framework, when an exception occurs, the system will determine what if anything is going to catch that exception before any finally blocks execute. Depending upon various application settings, an attempt to throw an exception which will not be caught may kill the application instantly, without giving any finally blocks (or anything else) a chance to run.
If one wraps the Main method, as well as each thread, in
try
{
...
}
catch
{
throw;
}
then any exception which is thrown within the try block will get caught. Even though it will be immediately re-thrown, any nested finally blocks will execute before the catch. There are some cases where this is desirable behavior; there are other cases where one may wish to e.g. perform some special logging if an exception isn't going to be caught (in some cases, the information one wishes to log may be destroyed if the finally blocks get a chance to run first). Within C#, there isn't any way to vary one's actions based upon whether an exception is going to be caught, but in VB.NET there are some ways via which that can be done; a VB.NET assembly which makes calls to C# code can give that code a way of knowing whether any exceptions thrown by an inner method will propagate out to the vb.net wrapper without being caught.
This does not appear to be the case in C#, however.
Is this what you are looking for.
As already stated, the finally block will always run once the catch block has been executed.
Edit: I just tried the sample code provided by the OP in a console application and lo and behold, it did not hit the finally block and had an error of "An unhandled exception of type 'System.Exception' occurred in ConsoleApplication1.exe". This was truly puzzling (besides the part of re-throwing the same exception in an endless loop) so I did a little investimagation and this is what I found:
If a exception occurs the CLR traverses up the call stack looking for
a matching catch expression. If the CLR doen't finds a matching one,
or the Exception gets re thrown each time, the Exception bubbles out
of the Main() method. In that case Windows handles the Exception.
Event Handling of Console Applications is the easiest to understand,
because there is no special Handling by the CLR. The Exception is
leaving the Applications Thread if not caught. The CLR opens a window
asking for debug or exit the application. If the user chooses to
debug, the debugger starts. If the user chooses to close, the
Application exits and the Exception is serialized and written to the
console.
Moral of the story, do not re-throw the same exception from a catch block in a console application!.

Proper way of using try catch() in C#

I am using ASP.NET/C#.
Here is an example where I am updating some information in database using lambda expression.
try
{
using (var db = new DataClasses1DataContext())
{
var logSubGroup = db.sys_Log_Account_SubGroups
.SingleOrDefault(subGroup => subGroup.cSubGroupName.Equals(subGroupName));
logSubGroup.cRejectedBy = rejectedBy;
logSubGroup.dRejectedOn = DateTime.Now;
logSubGroup.cAuthorizedStatus = "Rejected";
db.SubmitChanges();
}
}
catch (Exception ex)
{
}
As you can see I am not doing anything inside catch() block.
I know this is a terrible way of using try catch.
Can anyone just help me to use try catch block in a correct manner.
I am just clueless as to what must come inside the catch block.
Any suggestions are welcome.
Don't use a try-catch block at all, unless you have a specific reason to catch a specific exception.
Instead, use one of the global exception handling methods (Application_Error in ASP.NET) to globally catch unhandled exceptions, show an error message and log the error.
As a general rule, there is no need to catch an exception if the code catching the exception cannot do something about the problem, then continue running correctly. In code like what you've presented, can you identify some action you could take within the catch block to restore the program to a state where you trust it to continue running? If not, then just let the exception bubble up the stack.
You should ideally handle the error so that your application can recover from it, at the very least though, you should log it. You should never just swallow it. Also, you shouldn't handle an exception that you don't expect or can't handle. For example, when opening a file, a FileNotFoundException can be expected and handled, for example by displaying a warning and letting the user pick another file.
Theoretically it's up to you to decide what kind of exception may occur inside your catch statement it's not totally wrong doing it this way of course if you are in the development phase I would highly not recommend doing try catch since you can miss some of the important exception that may occur and you would want to fix also in general you should include a message or an action that should occur if the exception or error was caught a message to the user can be notified that action did not executed well but ideally you have to let user know what went wrong so in this case better error handling is a way to go

Try/Catch block not catching Exception

I have a statement inside a try/catch block, but the exception is not getting caught. Can anyone explain?
Exception Details:
System.NullReferenceException: Object
reference not set to an instance of an
object.
Source Error:
Line 139: try
Line 140: {
Line 141: return (int)Session["SelectedLeadID"];
Line 142: }
Line 143: catch (Exception ex)
Update
This is an ASP.NET application. In the catch block, a new exception is thrown. The code you see is what is displayed on the ASP.NET error page.
That catch block should catch the exception, but make sure there's no re-throwing in there.
Another small comment: I've been tricked quite a few times by VS, cause it breaks on exceptions like that while running in debug-mode. Try to simply press 'continue' or 'F5' and see if your application doesn't work anyway :)
I suspect you're going to need to add more detail - that isn't reproducible just from your code. In particular (as already noted) we'd need to see inside the catch, and verify that the exception is actually being thrown from inside the try and not somewhere else.
Other possibilities:
you have dodgy code inside the exception handler that is itself throwing an exception
you have a dodgy Dispose() that is getting called (using etc)
you are in .NET 1.1 and the thing getting thrown (in code not shown) isn't an Exception, but some other object
If it is only the debugger breaking on the exception and you are using VS2005 or above, you might want to check under Debug->Exceptions... if any of the Common-Language-Runtime-Exceptions are activated. If so, the debugger will always catch the exceptions first, but you are allowed to continue.
To revert to normal execution, simply uncheck the apropriate exceptions from the list.
I also faced this problem
Image
which was solved by removing the tick of
"Break when this exception type is thrown."
Warning:
Of course, I am not aware of the consequences of this.
I've also had such an issue and it was driving me nuts for quite some time, but in the end I figured it out. It's quite stupid, but maybe it might help someone:
public IActionResult SomeFunction()
{
try
{
return Json(new ClassWhichTakes2Parameters("FirstParameter"), "SecondParameter"); //comma placed in the wrong spot
}
catch (Exception ex)
{
//some code
}
}
It should have looked like:
public IActionResult SomeFunction()
{
try
{
return Json(new ClassWhichTakes2Parameters("FirstParameter", "SecondParameter"));
}
catch (Exception ex)
{
//some code
}
}
Since I had many return statements in that function I didn't catch this right away.
Also, the error message I've been receiving wasn't quite what I have expected at first, but now it makes sense:
System.InvalidOperationException: Property
'JsonResult.SerializerSettings' must be an instance of type
'Newtonsoft.Json.JsonSerializerSettings'.
The code looks terribly ugly IMO. For there to be something in the catch() block means you are going to have another return ... statement which AFAIK you should always have a single return statement at the end of each function to make following code easier.
i.e. maybe your code should look like
public int Function()
{
int leadID = 0;
try
{
int leadID = (int)Session["SelectedLeadID"];
}
catch (Exception ex)
{
...
}
return leadID
}
Single exit points are supposed to make the code easier to follow, I guess? Anyway, to get any useful help you have to post more of the function.

Categories