What is the right way to handle exception inside nested using statement? I have the following part of code:
public void Create(Entity entity)
{
try
{
using (ISession session = NhibernateHelper.OpenSession())
{
try
{
using (ITransaction transaction = session.BeginTransaction())
{
session.Save(entity);
transaction.Commit();
}
}
catch (TransactionException transactionException)
{
// log it
throw;
}
}
}
catch (TransactionException transactionException)
{
// log it
throw;
}
catch (SessionException sessionException)
{
// log it
throw;
}
catch (Exception exception)
{
// log it
throw;
}
}
I saw few answers when people put try/catch statement inside nested using. I know that using statement consists of try/finally. And my question is about right way to catch all possible exceptions. Should I do rollback inside one of catch statements? Could you provide me the right way to do it?
I tend to minimize "try catch" clauses as much as possible.
Nesting "try catch" and logging each catch (while not swallowing exception) may cause a same exception to be logged multiple times, which bloats the logs. And having "try catch" everywhere bloats the code.
I do not see the need for explicitly rollbacking a failed transaction : non committed transaction are rollbacked on dispose by default.
My usual pattern with MVC/webform is to use a global action filter (usually derived from HandleErrorAttribute) for logging exception, and/or a dedicated IHttpModule. So no need for "try catches" anywhere else just for logging while not swallowing the exception.
(With MVC, I usually explicitly rollback failed transaction because I am using an action filter for opening them OnActionExecuting, committing or rollbacking them OnActionExecuted depending on filterContext state. There, especially if there was an error, I may add a swallowing and logged try catch around the rollback: it may fails too, and I consider this failure should not mask the one having caused the app to try rollbacking.)
I follow the pattern of always beginning a try..catch block immediately after BeginTransaction().
Other than that, I think it's fine to not add any other exception checking - just let it propagate out to the calling code.
using (var session = NhibernateHelper.OpenSession())
{
using(var transaction = session.BeginTransaction())
{
try
{
//
// Add a block of code here which queries and
// modifies data
//
//
transaction.Commit();
}
catch(Exception ex)
{
transaction.RollBack();
throw;
}
}
}
Related
I couldn't think of a good way to test it myself so asking this question:
Lets say I have a list of transactions that I have sending them one by one to a web service and the result of webservice call may be Success, Failed or something weird may have happened and it just crashes.
So the overall code I have is like this:
for each (transaction)
{
try
{
string result = webservice.Call(transaction);
if result == "Faild"
{
// log some errors.
}
}
catch (Exception ex)
{
// Log some errors, stack trace, etc...
}
}
So my question is: if it falls into an exception for one of the transaction calls, then does the whole thing stop? OR it will get out of the exception block and will move on to next item in the for-each?
A catch is a catch and will do what a catch is supposed to do.
The loop will not break unless you rethrow the exception.
If you want to complete the entire loop before telling the user that something went wrong you can do
something like this:
List<Exception> exceptions = new List<Exception>();
foreach (var transaction in transactions)
{
try
{
string result = webservice.Call(transaction);
if result == "Faild"
{
// log some errors.
}
}
catch (Exception ex)
{
exceptions.Add(ex);
}
}
if (exceptions.Any())
throw new AggregateException(exceptions);
It WILL continue looping until you have no more transactions to loop through. That's what is so useful about try catch.
Since the try/catch is inside the loop, it will run for each transaction call.
If you had put the loop inside the try, then it would blow up at the first exception.
Check out the information here on using try { ... } catch() { ... } finally { ... }, where you can have code that executes after the exception is handled.
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
As I know that Using statement has built in implementation of Dispose() and Try-Catch. So I want to know few things
Is it possible to log an exception inside using statement without
using try-catch block , either inside or outside the statement. If
not, then why its built in to the statement.
Nested or overuse of try-catch is not preferred, then why such model
preferred to use.
using (some_resource)
{
try
{
}
catch
{
}
finally
{
//my exception logging mechanism
}
}
will become
try
{
try
{
}
catch
{
}
finally
{
//my exception logging mechanism
}
}
catch
{
}
finally
{
//some_resource.Dispose()
}
A using statement involves try/finally; there is no catch. But frankly, your concern is overkill; multiply-nested and complex try/catch/finally is "undesirable" because:
it makes the code hard to read
and even harder to get right (most people get it wrong, alas)
it is frequently misused
it suggests your method is doing too much
With using, this isn't an issue; it makes the intent very clean, without adding complexity or concern.
I would just use:
using (some_resource) {
try {
// some code
} catch (Exception ex) {
LogIt(ex);
throw;
}
}
Using compiles to Try{}Finally{}. See the following question: Does a C# using statement perform try/finally?
The reason for this is so that the resource will be disposed of regardless of if an exception is thrown. Resource disposal is the purpose of the using statement.
The correct implementation is:
using(Resource myresource = GetResource())
{
try
{}
catch(Exception e)
{ //Maybe log the exception here when it happens?
}
}
//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.. :)
Whatever is inside finally blocks is executed (almost) always, so what's the difference between enclosing code into it or leaving it unclosed?
The code inside a finally block will get executed regardless of whether or not there is an exception. This comes in very handy when it comes to certain housekeeping functions you need to always run like closing connections.
Now, I'm guessing your question is why you should do this:
try
{
doSomething();
}
catch
{
catchSomething();
}
finally
{
alwaysDoThis();
}
When you can do this:
try
{
doSomething();
}
catch
{
catchSomething();
}
alwaysDoThis();
The answer is that a lot of times the code inside your catch statement will either rethrow an exception or break out of the current function. With the latter code, the "alwaysDoThis();" call won't execute if the code inside the catch statement issues a return or throws a new exception.
Most advantages of using try-finally have already been pointed out, but I thought I'd add this one:
try
{
// Code here that might throw an exception...
if (arbitraryCondition)
{
return true;
}
// Code here that might throw an exception...
}
finally
{
// Code here gets executed regardless of whether "return true;" was called within the try block (i.e. regardless of the value of arbitraryCondition).
}
This behaviour makes it very useful in various situations, particularly when you need to perform cleanup (dispose resources), though a using block is often better in this case.
Because finally will get executed even if you do not handle an exception in a catch block.
any time you use unmanaged code requests like stream readers, db requests, etc; and you want to catch the exception then use try catch finally and close the stream, data reader, etc. in the finally, if you don't when it errors the connection doesn't get closed, this is really bad with db requests
SqlConnection myConn = new SqlConnection("Connectionstring");
try
{
myConn.Open();
//make na DB Request
}
catch (Exception DBException)
{
//do somehting with exception
}
finally
{
myConn.Close();
myConn.Dispose();
}
if you don't want to catch the error then use
using (SqlConnection myConn = new SqlConnection("Connectionstring"))
{
myConn.Open();
//make na DB Request
myConn.Close();
}
and the connection object will be disposed of automatically if there is an error, but you don't capture the error
Finally statements can execute even after return.
private int myfun()
{
int a = 100; //any number
int b = 0;
try
{
a = (5 / b);
return a;
}
catch (Exception ex)
{
Response.Write(ex.Message);
return a;
}
// Response.Write("Statement after return before finally"); -->this will give error "Syntax error, 'try' expected"
finally
{
Response.Write("Statement after return in finally"); // --> This will execute , even after having return code above
}
Response.Write("Statement after return after finally"); // -->Unreachable code
}
finally, as in:
try {
// do something risky
} catch (Exception ex) {
// handle an exception
} finally {
// do any required cleanup
}
is a guaranteed opportunity to execute code after your try..catch block, regardless of whether or not your try block threw an exception.
That makes it perfect for things like releasing resources, db connections, file handles, etc.
i will explain the use of finally with a file reader exception Example
with out using finally
try{
StreamReader strReader = new StreamReader(#"C:\Ariven\Project\Data.txt");
Console.WriteLine(strReader.ReadeToEnd());
StreamReader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
in the above example if the file called Data.txt is missing, an exception will be thrown and will be handled but the statement called StreamReader.Close(); will never be executed.
Because of this resources associated with reader was never released.
To solve the above issue, we use finally
StreamReader strReader = null;
try{
strReader = new StreamReader(#"C:\Ariven\Project\Data.txt");
Console.WriteLine(strReader.ReadeToEnd());
}
catch (Exception ex){
Console.WriteLine(ex.Message);
}
finally{
if (strReader != null){
StreamReader.Close();
}
}
Happy Coding :)
Note:
"#" is used to create a verbatim string, to avoid error of "Unrecognized escape sequence".
The # symbol means to read that string literally, and don't interpret control characters otherwise.
Say you need to set the cursor back to the default pointer instead of a waiting (hourglass) cursor. If an exception is thrown before setting the cursor, and doesn't outright crash the app, you could be left with a confusing cursor.
Sometimes you don't want to handle an exception (no catch block), but you want some cleanup code to execute.
For example:
try
{
// exception (or not)
}
finally
{
// clean up always
}
The finally block is valuable for cleaning up any resources allocated in the try block as well as running any code that must execute even if there is an exception. Control is always passed to the finally block regardless of how the try block exits.
Ahh...I think I see what you're saying! Took me a sec...you're wondering "why place it in the finally block instead of after the finally block and completely outside the try-catch-finally".
As an example, it might be because you are halting execution if you throw an error, but you still want to clean up resources, such as open files, database connections, etc.
Control Flow of the Finally Block is either after the Try or Catch block.
[1. First Code]
[2. Try]
[3. Catch]
[4. Finally]
[5. After Code]
with Exception
1 > 2 > 3 > 4 > 5
if 3 has a Return statement
1 > 2 > 3 > 4
without Exception
1 > 2 > 4 > 5
if 2 has a return statement
1 > 2 > 4
As mentioned in the documentation:
A common usage of catch and finally together is to obtain and use resources in a try block, deal with exceptional circumstances in a catch block, and release the resources in the finally block.
It is also worth reading this, which states:
Once a matching catch clause is found, the system prepares to transfer control to the first statement of the catch clause. Before execution of the catch clause begins, the system first executes, in order, any finally clauses that were associated with try statements more nested that than the one that caught the exception.
So it is clear that code which resides in a finally clause will be executed even if a prior catch clause had a return statement.