Proper usage of finally clause in try/catch block - c#

I'm trying to figure out the "best" way execute a (close) statement in my sql data access layer methods.
I was wondering which of the two ways is considered more correct (thanks):
Option #1
public void dbOperation( ... )
{
try
{
_cmd.Open();
_cmd.Execute();
}
catch (Exception ex)
{
throw ex;
}
finally
{
_cmd.Close()
}
}
Option #2
public void dbOperation( ... )
{
try
{
_cmd.Open();
_cmd.Execute();
}
catch (Exception ex)
{
_cmd.Close()
throw ex;
}
_cmd.Close();
}

Neither is correct. You shouldn't have a catch clause just to re-throw the exception again, clearing out its stack trace, and doing nothing productive, which is what your first option does.
You should just be closing in the finally:
try
{
_cmd.Open();
_cmd.Execute();
}
finally
{
_cmd.Close()
}
Your second snippet has the same problem with it, since you're improperly re-throwing the exception.
The best option would be to use a using, which is just a syntactic sugar for a try/finally without a catch:
using(var command = ...)
{
command.Open();
command.Execute();
}
This has the added benefit of also ensuring that the scope of the command is exactly the same as when it's valid to use it. A try/finally block requires the command to be a valid identifier after it has been disposed of.

Option #1 is the only correct one of the two. In fact, you can get the equivalent of option #1 using less code:
try
{
_cmd.Open();
_cmd.Execute();
}
finally
{
_cmd.Close()
}
If an exception is thrown, there's no need to have a catch block to just re-throw it. If you want to do something in the catch block, such as logging the exception, be sure to do this:
try
{
_cmd.Open();
_cmd.Execute();
}
catch (Exception ex)
{
logException(ex);
throw; //Just say throw, not throw ex, to preserve the original stack trace
}
finally
{
_cmd.Close()
}

Option #1. If you use option2 you won't execute cmd.close unless it throws an exception

Related

How to resume second method after first method throws an exception C#

While looking on C# try catch tutorial, I got following question. My sample code as follows,
Inside mainMethod() , I need to call three separate methods. Inside testMethodOne(), I need to handle exception as. If testMethodOne() throws exception, without executing testMethodTwo(dt), mainMethod() throwing exception. I need to call testMethodTwo(dt); and testMethodThreee(dt); if testMethodOne() throws exception, how can I do it.
public void MainMethod(data dt){
try{
testMethodOne(dt);
testMethodTwo(dt);
testMethodThreee(dt);
}catch(Exception ex){
throw ex;
}
}
public void testMethodOne(dt){
try
{
// Block of code to try
}
catch (Exception e)
{
// Block of code to handle errors
}
}
I understood your question as follows (but I might be wrong, your questions is not very clear):
Even if one of your testMethods throws an exception, you still want to continue in the normal program flow with the other methods. If at least one of the method failed, mainMethod could then report this as AggregateException.
public void MainMethod(data dt)
{
var exceptions = new List<Exception>();
try
{
testMethodOne(dt);
}
catch (Exception ex)
{
exceptions.Add(ex);
}
try
{
testMethodTwo(dt);
}
catch (Exception ex)
{
exceptions.Add(ex);
}
try
{
testMethodThreee(dt);
}
catch (Exception ex)
{
exceptions.Add(ex);
}
if (exceptions.Count > 0)
{
throw new AggregateException(exceptions);
}
}
It seems as if you want exceptions to alter the flow of your main method without breaking everything. One easy method is to make each 'testmethod' return a boolean.
public bool testMethodOne(dt){
try
{
// Block of code to try
return true;
}
catch (Exception e)
{
// Block of code to handle errors
return false;
}
}
Then in your main code you can go
if(!testMethodOne(dt))
if(!testMethodTwo(dt))
if(!testMethodThree(dt))
//log that all methods failed
The above snippet would try each method until it finds one that succeeds. If that's not the behaviour you are looking for can you reword your question to make it clearer? If you want the opposite to happen just get rid of the ! and it will go until one fails. Alternatively you could put a throw in your catch statement in each of the testMethods, and that would stop execution once one is reached as well.

Exception handling Try-Catch block difference

I know, we can use try-catch block to handle exceptions. But I have some doubts in the usage of Try-Catch.
What is the difference between
try
{
//Some code
}
catch
{
}
and
try
{
//Some code
}
catch(Exception)
{
}
and
try
{
//Some code
}
catch(Exception oops)
{
}
In my program, I need to catch all exceptions and I don't want to log them. From the above mentioned Try-Catch blocks, which should be used?
Using a catch without a parameter is no longer useful as of framework 2.0, as all unmanaged exceptions are wrapped in a managed exception. Before that you could use it to catch exceptions thrown by unmanaged code.
You can specify just the type of the exception if you don't want to use any information from it, but usually you would want a name for it so that you can get to the information:
try {
// some code
} catch(Exception) {
// i don't care about any information in the Exception object, just the type
}
vs.
try {
// some code
} catch(Exception ex) {
// use some information from the exception:
MessageBox.Show("Internal error", ex.Message);
}
You should always try to have an exception type that is as specific as possible, as that makes it easier to handle the exception. Then you can add less specific types to handle other exceptions. Example:
try {
// some database code
} catch(SqlException ex) {
// something in the database call went wrong
} catch(Exception ex) {
// something else went wrong
}
So far you use catch (Exception), the first and the second are the same. You catch everything in this case. When you like to catch a specific exception like UnauthorizedAccessException, you have to use the second one like this:
try
{
//Some code
}
catch (UnauthorizedAccessException)
{
MessageBox.Show(oops.Message);
}
In the third case you can use the Exception through the variable oops.
For example:
try
{
//Some code
}
catch (Exception oops)
{
MessageBox.Show(oops.Message);
}
Or with a specific exception:
try
{
//Some code
}
catch (UnauthorizedAccessException oops)
{
MessageBox.Show(oops.Message);
}
Generic try catch, this will catch any type of exception
try
{
//Some code
}
catch
{
}
This will catch the specific type of exception that you specify, you can specify multiple.
try
{
}
catch (UnauthorizedAccessException)
{
}
This will do the same as above but give you a variable that has access to the properties of an exception.
try
{
}
catch (UnauthorizedAccessException ex)
{
}
You should be using the last one, and handling in a clean way your exception.
The first too way are the same but are "Eating Exceptions", witch is the worst thing to do.
At least log your exception!
Your first and second example are the same. They will both catch any exception, without any information about the exception. The third exception stores the exception in oops, which you can then use to get more information about the exception.
Look at msdn documentation: http://msdn.microsoft.com/en-us/library/vstudio/0yd65esw.aspx
The best is specify which kind of errors you would like catch.
The third one is the best...
You can catch any kind of specific exception and it will be precise... This helps in identifying the exact exception and easy for us to correct them as well
For eg: one can catch DivisionByZeroException, TargetInvocationException, ArrayOutOfBoundException, etc...
They are all pretty much the same (I assume the first is shorthand for writing the 2nd), the difference with the last is you are putting the exception object into a variable so you can use it in the catch.
Usually when I see code like this I tend to worry as it's generally not a good idea as you could be masking bigger problems with your application.
Rule of thumb - handle what you can, let everything else bubble up.
i think it has the same function - To trace where the error is set/ or where did something get wrong,
using try-catch this way
> try {
//some codes
}
catch
{
//anything
//e.g.:
MessageBox.Show("Something is wrong!");
}
this tells the that there is something wrong but didn't show the detailed report. (Clever way to hide some errors is don't put anything in the catch{} xD, but this is not advised to do)
the next is to show detailed report of the error
try
{
//some codes
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
hope this helps! :D

C# - Exception handling from within finally clause

The title is a bit misleading but the issue seems very straight-forward to me. I have try-catch-finally block. I want to execute the code in the finally block only if an exception was thrown from the try block. The structure of the code right now is:
try
{
//Do some stuff
}
catch (Exception ex)
{
//Handle the exception
}
finally
{
//execute the code only if exception was thrown.
}
Right now the only solution I can think of is setting a flag like:
try
{
bool IsExceptionThrown = false;
//Do some stuff
}
catch (Exception ex)
{
IsExceptionThrown = true;
//Handle the exception
}
finally
{
if (IsExceptionThrown == true)
{
//execute the code only if exception was thrown.
}
}
Not that I see something bad in this but wonder if there is another(better) approach to check if there's a thrown exception?
What about something like:
try
{
// Do some stuff
}
catch (Exception ex)
{
// Handle the exception
// Execute the code only if exception was thrown.
}
finally
{
// This code will always be executed
}
That's what Catch block are made for!
Don't use finally for this. It is intended for code that should always execute.
What exactly is the difference, in terms of when to execute, between
//Handle the exception
and
//execute the code only if exception was thrown.
I can't see any.
You don't need finally after all:
try
{
//Do some stuff
}
catch (Exception ex)
{
//Handle the exception
//execute the code only if exception was thrown.
}
The Finally part of a Try / Catch statement is always fired regardless of whether any exceptions have been found. I would recommend you don't use it in this scenario.
try
{
// Perform Task
}
catch (Exception x)
{
//Handle the exception error.
}
Finally
{
// Will Always Execute.
}

If exception occurs in Catch block itself then how to handle it in C#?

//I have written code in Catch Block
try {
} catch(Excepetion ex) {
// I have written code here If Exception Occurs then how to handle it.
}
You can put a try catch inside the catch block, or you can simply throw the exception again. Its better to have finally block with your try catch so that even if an exception occurs in the catch block, finally block code gets executed.
try
{
}
catch(Excepetion ex)
{
try
{
}
catch
{
}
//or simply throw;
}
finally
{
// some other mandatory task
}
Finally block may not get executed in certain exceptions. You may see Constrained Execution Regions for more reliable mechanism.
The best way is to develop your own exceptions for different Layers of application and throw it with inner exception. It will be handled at the next layer of your application. If you think, that you can get a new Exception in the catch block, just re throw this exception without handling.
Let's imagine that you have two layers: Business Logic Layer (BLL) and Data Access Layer (DAL) and in a catch block of DAL you have an exception.
DAL:
try
{
}
catch(Excepetion ex)
{
// if you don't know how should you handle this exception
// you should throw your own exception and include ex like inner exception.
throw new MyDALException(ex);
}
BLL:
try
{
// trying to use DAL
}
catch(MyDALException ex)
{
// handling
}
catch(Exception ex)
{
throw new MyBLLException(ex);
}
try
{
// Some code here
}
catch (Exception ex)
{
try
{
// Some more code
}
catch (Exception ex)
{
}
}
For the lines of code that could throw an exception in catch block make extra explicit try..ctach block. Besides consider having finally block, to have lines to run by all means there. The same question may raise for the finally block. So if your code is likely to throw some exception in the finally block, you could also add try..catch there.
try
{
}
catch (Exception ex)
{
try
{
// code that is supposed to throw an exception
}
catch (Exception ex1)
{
}
// code that is not supposed to throw an exception
}
finally
{
try
{
// code that is supposed to throw an exception
}
catch (Exception ex1)
{
}
// code that is not supposed to throw an exception
}
Double-faulting often happens in well-designed 3g programming languages. Since protected mode and the 286, the general design for hardware languages is to reset the chip on a triple fault.
You are probably ok designing your way out of a double fault. Don't feel bad about having to do something to stop processing / report an error to the user in this case. If you run into a case where, eg., you catch an IO exception (reading/writing data) and then try to close the stream you're reading from, and that also fails, its not a bad pattern to fail dramatically and warn the user that something truly exceptional happened.
A catch block isn't special in any particular way. You will have to either use another try/catch block or not handle the error.
My friend Atul.. if you if write try..catch in catch block, and if again exception occurs in inner try..catch, same problem will raise again.
So address this issue you can handle those errors in application level events in Global.asax
check below links..
http://msdn.microsoft.com/en-us/library/24395wz3%28v=vs.100%29.aspx
http://msdn.microsoft.com/en-us/library/fwzzh56s%28v=vs.80%29.aspx
let me know if this works for you.. :)

Calling methods which might throw inside catch

Let us say we have an external server which we use (e.g.-telephony station, etc.). Also we have the next code:
try
{
externalService.CreateCall(callParams);
}
catch (Exception ex)
{
_log.Error("Unexpected exception when trying execute an external code.", ex);
_callService.UpdateCallState(call, CallState.Disconnected, CallOutcome.Failed);
throw;
}
Theoretically UpdateCallState could throw but we would hide this exception using that code and would treat only exceptions generated by CreateCall in a right way.
The question is, what is the right pattern for these situations so that we treat all the exceptions correctly?
You can always nest another try..catch inside the first catch and deal with it appropriately.
try
{
externalService.CreateCall(callParams);
}
catch (Exception ex)
{
_log.Error("Unexpected exception when trying execute an external code.", ex);
try
{
_callService.UpdateCallState(call, CallState.Disconnected, CallOutcome.Failed);
}
catch(Exception updateEx)
{
// do something here, don't just swallow the exception
}
throw; // this still rethrows the original exception
}
Break it up. Something like
if !TryCreateExternalCall(callParams)
{
_log.Error("Unexpected exception when trying execute an external code.", ex);
_callService.UpdateCallState(call, CallState.Disconnected, CallOutcome.Failed);
}
else
{
throw new ExternalServiceException(???);
}
TryCreateExternalCall should of course log the exception and stacktrace, before it swallows and returns false.
It is not a good practice to throw exception in Catch block.
The try, Catch suggest that
try
{
//make some changes. If something goes wrong go to Catch.
}
Catch(exception)
{
//I will clean the mess. Rollback the changes.
}
Catch the exception, only if you can handle the exception. Else bubble it up let the caller decide on what to do with the exception.
You should catch the most specific exception first, followed by the most general exceptions.
try
{
externalService.CreateCall(callParams);
}
catch (CreateCallExceptionType ccEx)
{
_callService.UpdateCallState(call, CallState.Disconnected, CallOutcome.Failed);
}
catch (Exception ex)
{
//do something
}
And then you could handle the UpdateCallState exception within the method.

Categories