try
{
operation1();
operation2();
...
}
finally
{
try
{
finalizer_operation1();
finalizer_operation2();
}
finally
{
very_critical_finalizer_operation_which_should_occurs_at_the_end();
}
}
Is this ok? To have finalizer as another try/finally block (because finalizer_operationX() may throw and I must ensure that very_critical...() will happens at the end.
Quick googling for try in finally block brings nothing (will delete question if you give me a duplicate link), it should work, but I am unsure in design and possible problems with it.
I would not write the code this way. I don't like nesting try/catch/finally constructs. I prefer one per method.
My preference is to wrap each of those calls in its own method.
try
{
operation1();
operation2();
...
}
finally
{
cleanup();
}
public void cleanup() {
try
{
finalizer_operation1();
finalizer_operation2();
}
finally
{
very_critical_finalizer_operation_which_should_occurs_at_the_end();
}
}
Of course it is. A finally block will execute if control flow enters the corresponding try block.
The only exception is a call that shuts down the VM.
Related
The MSDN recommends putting any instantiation of classes that implement IDisposable into a using block. Or alternatively, if it is being instantiated within a try-catch block, then Dispose in Finally.
Are there any problems with using a using block within a try-catch block like so?
try
{
using (Foo bar = new Foo())
{
bar.doStuff();
}
}
catch (Exception e)
{
//vomit e
}
Of course I can just call Dispose in a Finally block, but I'm a newbie to programming and I'm just curious to know if doing something like this is practically acceptable or if someone would smack me up the back of my head and yell at me that I'm Doing-It-Wrong™.
Or rather, I'm more interested in knowing why this would be wrong if it is.
No, that looks perfectly fine. Your bar instance will be disposed before you even get into the catch block.
This is... drum roll... absolutely fine.
The only issue is that you shouldn't use catch (Exception), but catch the specific errors you're interested in (even if this is just an example), but that has no bearing on the using. In fact, the only reason why you would put the using outside the try block is because you want to continue doing something with bar that's unrelated to the code that failed -- otherwise, keeping the scope as small as possible is generally a good idea.
It is OK but you lost access to object that would have caused the exception in the exception.
And catching general exceptions is not considered a good practice
Foo bar = null;
try
{
bar = new Foo();
bar.doStuff();
}
catch (IndexOutOfRangeException e)
{
//vomit e
Debug.WriteLine(e.msg);
if(bar == null)
Debug.WriteLine("bar = new Foo() failed ");
else
Debug.WriteLine("bar fail ID = " + bar.ID);
}
catch (Exception e)
{
// ...
// unless you are going to handle it gracefully you should rethrow it
}
finally
{
if(bar != null) bar.Dispose();
}
Your example code is redundant. The Using() documentation states:
A using statement of the form
using (ResourceType resource = expression)
statement corresponds to one of two possible expansions. When ResourceType is a value type, the expansion is
{
ResourceType resource = expression;
try {
statement;
}
finally {
((IDisposable)resource).Dispose();
}
}
Otherwise, when ResourceType is a reference type, the expansion is
{
ResourceType resource = expression;
try {
statement;
}
finally {
if (resource != null) ((IDisposable)resource).Dispose();
}
}
In either expansion, the resource variable is read-only in the embedded statement.
Your code will ultimately look something like:
try
{
Foo bar = new Foo()
try
{
bar.doStuff();
}
finally
{
if (bar != null) ((IDisposable)bar).Dispose();
}
}
catch (Exception e)
{
//vomit e
}
No real reason for two try statements. It's not wrong code, it's just redundant in the context of multiple try statements. You question appears to be about Disposing of an object. In this context, it is redundant. If you are also concerned about the object constructor throwing an exception, the obviously this would be needed.
Are there any problems with using a using block within a try-catch block like so?
No, I write your example all the time.
Of course I can just call Dispose in a Finally block,
Sort of, the constructor must be called outside the try/catch, otherwise the variable will be out of scope by the time you reach the finally block
valid:
var foo = new bar();
try
{
}
finally
{
foo.Dispose();
}
invalid:
try
{
var foo = new bar();
}
finally
{
foo.Dispose();
}
No, it is fine, but if you want to access bar during the catch, you'll need an inner try catch:
try
{
using (Foo bar = new Foo())
{
try
{
bar.doStuff();
}
catch (Exception e)
{
//vomit e, with bar available.
}
}
}
catch (Exception e)
{
//vomit e, relating to a problem during creation of Foo.
}
or, as suggested in the comments, factor out the inner block into a new method.
Is it possible to detect if the same thread trying to release the lock?
We have many places in code that looks like:
try
{
try
{
if(!Monitor.TryEnter(obj, 2000))
{
throw new Exception("can not lock");
}
}
finally
{
Monitor.Exit(obj);
}
}
catch
{
//Log
}
The above code very simplified, and actually Enter and Exit statement located in custom object (lock manager).
The problem, that in that structure, we have SynchronizationLockException when trying to "Exit", since it looks like the thread that not succeed to lock, tries to release in finally.
So the question, is how I can know if the thread who making Monitor.Exit is the same thread who did Monitor.Enter?
I thought that I can use CurrentThread.Id to sync enter and exit, but I'm not sure if it "safe" enough.
So the question, is how I can know if the thread who making Monitor.Exit is the same thread who did Monitor.Enter?
You can't, easily, as far as I'm aware. You can't find out which thread owns a monitor.
However, this is just a coding issue - you should change your code so that it doesn't even attempt to release the monitor when it shouldn't. So your code above could be rewritten as:
if (!Monitor.TryEnter(obj, 2000))
{
throw new Exception(...);
}
try
{
// Presumably other code
}
finally
{
Monitor.Exit(obj);
}
Or even better, if you're using .NET 4, use the overload of TryEnter which accepts an ret parameter:
bool gotMonitor = false;
try
{
Monitor.TryEnter(obj, ref gotMonitor);
if (!gotMonitor)
{
throw new Exception(...);
}
// Presumably other code
}
finally
{
if (gotMonitor)
{
Monitor.Exit(obj);
}
}
As you think that to put the calling of Monitor.Exit in try-catch was 'durty'(dirty?), here's a very simple idea trying to 'take the durty away'. Lock is reentrant for the same thread and if one thread acquired successfully, before it releases, attempt from another thread will fail. So that you can consider something like:
public void Exit(object key) {
if(!IsActive) {
return;
}
if(LockDictionary.ContainsKey(key)) {
var syncObject=LockDictionary[key];
if(Monitor.TryEnter(syncObject.SyncObject, 0)) {
SetLockExit(syncObject);
Monitor.Exit(syncObject.SyncObject);
Monitor.Exit(syncObject.SyncObject);
}
}
}
We call Monitor.Exit twice because we lock it twice, one in the code outer, and one just here.
I know this is an older question, but here's my answer anyway.
I would move the try-finally construct inside the if:
try
{
if(Monitor.TryEnter(obj, 2000))
{
try
{
// code here
}
finally
{
Monitor.Exit(obj);
}
}
else
{
throw new Exception("Can't acquire lock");
}
}
catch
{
// log
}
I have a question that might seem fairly simple (of course if you know the answer).
A certain function I have calls another function but I want to continue execution from the caller even though the callee has thrown an exception. Let me give you an example:
something function1()
{
try
{
//some code
int idNumber = function2();
//other code that need to execute even if function2 fails
return something;
}
catch(Exception e)
{//... perhaps something here}
}
EDIT: function1 also has a return statement so nothing can in fact crash on the way
In function2 I need to do stuff but I only need to log if anything fails, example:
int function2()
{
try
{
//dostuff
}
catch(Exception e)
{
//Log stuff to db
}
}
ok, now my question is, what should I do if I wanted to continue execution in function1 even if function 2 throws an error?
Sometimes I mix up if I should do throw; or throw e; or throw nothing at all (leave catch block empty)
Leaving the catch block empty should do the trick. This is almost always a bad idea, though. On one hand, there's a performance penalty, and on the other (and this is more important), you always want to know when there's an error.
I would guess that the "callee" function failing, in your case, is actually not necessarily an "error," so to speak. That is, it is expected for it to fail sometimes. If this is the case, there is almost always a better way to handle it than using exceptions.
There are, if you'll pardon the pun, exceptions to the "rule", though. For example, if function2 were to call a web service whose results aren't really necessary for your page, this kind of pattern might be ok. Although, in almost 100% of cases, you should at least be logging it somewhere. In this scenario I'd log it in a finally block and report whether or not the service returned. Remember that data like that which may not be valuable to you now can become valuable later!
Last edit (probably):
In a comment I suggested you put the try/catch inside function2. Just thought I would elaborate. Function2 would look like this:
public Something? function2()
{
try
{
//all of your function goes here
return anActualObjectOfTypeSomething;
}
catch(Exception ex)
{
//logging goes here
return null;
}
}
That way, since you use a nullable return type, returning null doesn't hurt you.
Why cant you use the finally block?
Like
try {
} catch (Exception e) {
// THIS WILL EXECUTE IF THERE IS AN EXCEPTION IS THROWN IN THE TRY BLOCK
} finally {
// THIS WILL EXECUTE IRRESPECTIVE OF WHETHER AN EXCEPTION IS THROWN WITHIN THE TRY CATCH OR NOT
}
EDIT after question amended:
You can do:
int? returnFromFunction2 = null;
try {
returnFromFunction2 = function2();
return returnFromFunction2.value;
} catch (Exception e) {
// THIS WILL EXECUTE IF THERE IS AN EXCEPTION IS THROWN IN THE TRY BLOCK
} finally {
if (returnFromFunction2.HasValue) { // do something with value }
// THIS WILL EXECUTE IRRESPECTIVE OF WHETHER AN EXCEPTION IS THROWN WITHIN THE TRY CATCH OR NOT
}
Or you can encapsulate the looping logic itself in a try catch e.g.
for(int i = function2(); i < 100 /*where 100 is the end or another function call to get the end*/; i = function2()){
try{
//ToDo
}
catch { continue; }
}
Or...
try{
for(int i = function2(); ; ;) {
try { i = function2(); return; }
finally { /*decide to break or not :P*/continue; } }
} catch { /*failed on first try*/ } finally{ /*afterwardz*/ }
just do this
try
{
//some code
try
{
int idNumber = function2();
}
finally
{
do stuff here....
}
}
catch(Exception e)
{//... perhaps something here}
For all intents and purposes the finally block will always execute. Now there are a couple of exceptions where it won't actually execute: task killing the program, and there is a fast fail security exception which kills the application instantly. Other than that, an exception will be thrown in function 2, the finally block will execute the needed code and then catch the exception in the outer catch block.
Do you mean you want to execute code in function1 regardless of whether function2 threw an exception or not? Have you looked at the finally-block? http://msdn.microsoft.com/en-us/library/zwc8s4fz.aspx
In your second function remove the e variable in the catch block then add throw.
This will carry over the generated exception the the final function and output it.
Its very common when you dont want your business logic code to throw exception but your UI.
how can I do that ?
void x()
{....
if (...)
{try
{}
catch (ComException com)
{ throw com}
finally // in any case, executed fine!
{...instructions.......}
}
... instructions...// not executed in case of exception because the finally can't embrace the following code too... but this block of code needs to be executed in any case too...
{}
}
That's incorrect logic. The else block will not be executed if the code goes into the if statement.
If you really need it to be executed even in case of exception, copy the code from the else block into the finally block.
EDIT: So I think what you want is this:
try
{
if()
{
try
{
//Code
}
catch(ComException e)
{
throw e;
}
}
}
finally
{
/*....instructions.....*/
}
The reasoning behind this is that the inner try will execute the code if the IF statement is true, and will catch and then re-throw the ComException if it encounters it. The code in the finally block will execute regardless of either the IF statement or the catching of a ComException.
Does this explain the position better?
With apologies to dtb; he answered this first, I just added an explanation.
Move the code in the "else" branch to a separate method. Then call that method from both the "else" and the "finally".
Are you looking for this?
try
{
if (...)
{
try
{
...
}
catch (ComException)
{
...
}
}
}
finally
{
...
}
The finally block is executed regardless of whether the condition holds or not.
If something needs to be executed, it must go in the finally block. Finally always executes, no matter what happens in try and catch blocks. The context of the "else" is really outside your try/catch/finally segment.
Simple best practice question.
Should you nest try catch statements or just use methods.
For instance, if you have a method that opens a file does work and closes the file, you would have the open and close outside the try catch, or rather the close in the finally block.
Now if your open method fails, the method would assert right? So should your wrap that in a try catch block or should that be called from another method, which in turn as a try catch block?
In the context of a method that opens a file I would use a using statement vs a try catch. The using statement ensures that Dispose is called if an exception occurs.
using (FileStream fs = new FileStream(file, FileMode.Open))
{
//do stuff
}
does the same thing as:
FileStream fs;
try
{
fs = new FileStream(file, FileMode.Open);
//do Stuff
}
finally
{
if(fs!=null)
fs.Dispose();
}
Now that we have lambdas and type inference and some other stuff, there's an idiom that is common in other languages which now makes a lot of sense in C#. Your example was about opening a file, doing something to it, and then closing it. Well, now, you can make a helper method which opens a file, and also takes care of making sure to close / dispose / clean up, but calls out to a lambda you provide for the "do stuff" portion. This will help you get the complicated try/catch/finally dispose/cleanup stuff right in one place, and then use it over and over.
Here's an example:
public static void ProcessFile(string filePath, Action<File> fileProcessor)
{
File openFile = null;
try
{
openFile = File.Open(filePath); // I'm making this up ... point is you are acquiring a resource that needs to be cleaned up after.
fileProcessor(openFile);
}
finally
{
openFile.Close(); // Or dispose, or whatever.
}
}
Now, callers of this method don't have to worry about how to open the file or close / dispose of it. They can do something like this:
Helpers.ProcessFile("C://somefile.txt", f =>
{
while(var text = f.ReadLine())
{
Console.WriteLine(text);
}
});
This is a style question but for me I try to never have more than one level of try/catch/finally nesting in a single method. At the point you hit a nested try, you've almost certainly violated the 1 function = 1 operation principal and should use a second method.
Depends on what you are trying to do, but in most cases, nested try/catches are a sign of an over-complex function (or of a programmer who doesn't quite know how exceptions work!).
In the case of the open file, I'd use an IDisposable holder and a using clause, and so forgo the need of any explicit try/catch.
How about where you have related code that doesn't necessarily belong in a separate function of it's own right? Would this then be correct?
try
{
// Part 1 Code Here
try
{
// Part 2 Code Here
}
catch (Exception ex)
{
// Error from Part 2
}
}
catch (Exception ex)
{
// Error from Part 1
}
Most of the time I would break up the nested try/catch blocks into functions. But I have sometimes written code to catch and log all uncaught exceptions thrown by my application. But what if the logging code fails? So I have yet another try/catch around that just to prevent the user from seeing the default .NET unhandled exception dialog box. But even this code could very easily be refactored into functions instead of nested try/catch blocks.
try
{
try
{
DoEverything();
}
catch (Exception ex)
{
// Log the exception here
}
}
catch (Exception ex)
{
// Wow, even the log is broken ...
}
//create a switch here and set it to 0
try
{
DoChunk1();
//looks good. set the switch to 1
}
catch (Exception ex)
{
// Log the exception here
}
// check the switch, if it is still zero at this point then you may halt your program here; else set the switch back to zero and execute your next try catch statement. totally agree with breaking them down as mentioned above
try
{
DoChunk2();
//looks good. set the switch to 1
}
catch (Exception ex)
{
// Log the exception here
}
try
{
----
}
catch
{
try
{
---
}
catch
{
---
}
}