try-catch every db connection? - c#

Is it recommended to put a try-catch block in every function that opens a DB connection and log the error there, or should I rather catch errors in a higher layer of the application?
public static Category GetCategoryByName(string name)
{
Category result;
try
{
using (IDbConnection conn = ConnectionHelper.CreateDbConnectionByName(_connectionStringName))
{
conn.Open();
using (IDbCommand cmd = conn.CreateCommand())
{
//do stuff
}
}
}
catch(Exception e)
{
// log error here?
}
return result;
}
or rather
try
{
Category myCat = DataTools.GetCategoryByName("myCat");
// other stuff
}
catch(Exception e)
{
// log error here?
}
To sum it up: Should errors be caught as early as possible in the code? Or should I rather catch them where I have more information about the context?

As always, it depends, but in general, only catch an exception if you can do something about it, or you have specific code (e.g. a retry) to happen, or if you wish to take a very general exception and wrap it into an exception that is more specific for your business logic, otherwise, let the exception bubble up and the top most layer can log it/deal with it in a centralised fashion.
Any other way results in a lot of logging code interspersed with all the business logic.

When catching exceptions, always try to use the most accurate exception you can. For example, when using SQL Server, catch the SqlException as it will contain far more information about the exceptin than a generic Exception. You can get actual line numbers and other useful pieces of diagnostic information.
After you have extracted and logged all that is relevent, rethrow the exception or wrap it in less specific exception such as an InvalidDataException or Exception and throw that. You can then catch these more generic exceptions at higher levels.
try
{
// Execute DB call here
}
catch(SqlException exp)
{
// Log what you need from here.
throw new InvalidOperationException("Data could not be read", exp);
}
When you call this method from a higher level, you can just catch the InvalidOperationException. If the higher levels do need more detail, the InnerException will provide the SqlException which can be accessed.
The general approach to exception handling that I follow is to only catch what I can usefully act upon. There no point in catching really general Exception at lower levels of the code since you can really expect everything to go wrong or to be able to recover from every exception e.g. OutOfMemoryException or StackOverflowException.

I Usually only handle exceptions in the UI, everything below that I always throw it back to the top level. This way the stack trace has been maintained all the way though. You could always log and throw it.
I have used this before also:
try
{
DB Command
}
catch (Exception ex)
{
Log(ex)
throw; //preserve stacktrace
}

I like the first approach better, but you still have to work out what else to do i the catch block...
rethrow the exception?
throw another (more general) exception?
return null to the caller?

Related

is there any way to catch original exception if another exception raise during handeling that in C#?

assume we have following peace of code in C#:
try{
....
try{
throw new Exception1("exception1");
}catch(Exception exception){
...
throw new Exception2("exception2");
}
}catch(Exception exception){
...
log(exception.message);
}
is it possible in log point(outer catch) to access exception1 object and log that one as well?
Here are two reasonable examples of what I think you are talking about. They illustrate what I was trying to describe in the comments as well as what #Jonesopolis describes.
First, my case. Say you are writing a utility that calls some lower-level service that may throw. You may want to describe the behavior of the utility in a way that the exceptions that may bubble up have more meaning to the caller. In this case, I've documented that my utility will throw an ApplicationException if there is a problem.
I do this from two places, the first one when I check some pre-conditions (that the path name is neither null or empty and that it is a valid file name (I'm assuming that there is an IsValidFileName function I can call)).
But the other place is that if I try to do the operation and it throws (I haven't checked that File.ReadAllLines actually ever throws an IOException, but I'm guessing it can). In this case, I don't want to burden my users with catching a possible IOException, instead, I translated it into an ApplicationException that I document. I wrap the IOException with a catch and throw of my ApplicationException, but I include the IOException as the inner exception so that debugging and tracking down other issues works. The code looks like:
public IEnumerable<string> AccessFile(string pathName)
{
if (string.IsNullOrEmpty(pathName) || !IsValidFileName(pathName))
{
throw new ApplicationException("Invalid Path Name");
}
try
{
var result = File.ReadAllLines(pathName);
return result;
}
catch (IOException ex)
{
throw new ApplicationException("Error Accessing File", ex);
}
}
It's that second parameter to the ApplicationException that sets up the inner exception. This pattern is very common.
The other example is what #Jonesopolis describes.
Here I have a work function doing something. My application architecture demands that I do logging at the level of whatever the DoSomethingImportant function is at. So, it catches any exceptions that get thrown at a lower level. However, that code wants to bubble up any exceptions to the DoSomethingImportant function's caller. Here, it just uses the throw keyword with no argument. That rethrows the current exception and lets it bubble through.
It's important to use throw; with no arguments, and not throw ex;. The former allows the existing exception to bubble up. The latter unwinds the stack at the catch site, and then throws a new exception, losing all the stack information that might point to the faulting location.
This is the typical code that I'm talking about. It's also a very common pattern:
public void DoSomethingImportant()
{
try
{
DoSomethingLowLevel();
}
catch (Exception ex)
{
GetLogger().Log(ex);
throw;
}
}

Exceptions to Never Catch

I know that there are some exception types that cannot be caught in catch blocks, like StackOverflowException in .NET 2.0. I would like to know which other exceptions are inadvisable to catch, or are associated with bad practices.
The way I would like to use this list of exception types is to check it every time I am using Exception in a catch block:
private static readonly Type[] _exceptionsToNotCatch = new Type[] { typeof(StackOverflowException) };
// This should never throw, but should not swallow exceptions that should never be handled.
public void TryPerformOperation()
{
try
{
this.SomeMethodThatMightThrow();
}
catch (Exception ex)
{
if (_exceptionsToNotCatch.Contains(ex.GetType()))
throw;
}
}
EDIT
I don't think I provided a very good example. That's one of the problems with trying to make an example trivial when trying to communicate one's meaning.
I never throw Exception myself, and I always catch specific exceptions, only catching Exception as follows:
try
{
this.SomeMethodThatMightThrow();
}
catch (SomeException ex)
{
// This is safe to ignore.
}
catch (Exception ex)
{
// Could be some kind of system or framework exception, so don't handle.
throw;
}
My question was meant as more of an academic one. What exceptions are only thrown by the system and should never be caught? I am worried about situations more like this:
try
{
this.SomeMethodThatMightThrow();
}
catch (OutOfMemoryException ex)
{
// I would be crazy to handle this!
// What other exceptions should never be handled?
}
catch (Exception ex)
{
// Could be some kind of system or framework exception, so don't handle.
throw;
}
This question was really inspired by the following:
System.Data.EntityUtil.IsCatchableExceptionType(Exception) in System.Data.Entity, Version=3.5.0.0
I would like to know which other exceptions are inadvisable to catch, or are associated with bad practices.
Here is the list of all exceptions you shouldn't catch:
Any exception you don't know what to do with
Here's the best practice for exception handling:
If you don't know what to do with an exception, don't catch it.
This may sound snarky, but they're both correct, and that's all you need to know.
It's generally not a good idea to do that.
You should catch the most specific exception(s) possible and only carry on execution of your program when it is safe to do so. E.g. if you're opening a file, it's perfectly reasonable to catch exceptions relating to file access / permission errors, but probably not much else. You certainly wouldn't want to catch an OutOfMemoryException and then blindly carry on. They're very different errors!
If you apply a blanket rule of what to catch, there's no guarantee that your program will be able to continue execution safely because you're not responding to specific situations, just applying a one size does not fit all solution.
Using Exception in the catch block would catch all exceptions that are catchable. I would say you should specify only exceptions that needs to be caught and let the ones you don't want to catch spill out. E.g.
try
{
}
catch(SqlException sqlex) //specific to database calls
{
//do something with ex
}
catch(FormatException fex) //specific to invalid conversion to date, int, etc
{
//do something with ex
}
catch(Exception ex)
{
//I didn't know this exception would be thrown
//log it for me or Rethrow it
}
Any other exception not in that list will not be caught
Okay so we've established it ain't a good idea. And we've established that programmers on SO prefer to opine from their high-horses rather than hand you a knife to stab yourself with, so for those with suicidal tendencies, let's start with these:
(Redacted my list and DRYing-up SO to point to Hans' list)
https://stackoverflow.com/a/5508733/17034

throw exception in the try block rather than catch block?

I've inherited code in our project which looks like this. It's a method in a class.
protected override bool Load()
{
DataAccess.SomeEntity record;
try
{
record = _repository.Get(t => t.ID.Equals(ID));
if (record == null)
{
throw new InvalidOperationException("failed to initialize the object.");
}
else
{
this.ID = record.ID;
// this.OtherProperty = record.SomeProperty;
// etc
}
}
catch (Exception)
{
throw;
}
return true;
}
If I then call this Load method from my UI layer, I'd probably want to have a try catch block to catch any exception caused by the failure to Load the instance, e.g. InvalidOperationException, but the above code feels wrong to me.
Won't the InvalidOperationException be swallowed by the catch statement? that catch statement will also catch potential problems with _repository.Get, as well as potential problems with the setting of properties if the record is valid.
I thought I should perhaps restructure it by adding more try catch statements to handle the Get operation and property setting operations separately, or add more catch blocks handling different exceptions, but I asked a colleague, and he suggested that the try catch is irrelevant in this case, and should be removed completely, leaving it like:
protected override bool Load()
{
DataAccess.SomeEntity record;
record = _repository.Get(t => t.ID.Equals(ID));
if (record == null)
{
throw new InvalidOperationException("failed to initialize the object.");
}
else
{
this.ID = record.ID;
// this.OtherProperty = record.SomeProperty;
// etc
}
return true;
}
I'd like some second opinions, I've only just started taking an interest in exception handling, so I'd like to make sure I am doing it the right way according to best practices.
When you do this:
catch (Exception)
{
throw;
}
You are essentially not handling the exception. That does not however mean you are ignoring it. The throw statement will propagate the exception up the stack. For the sake of clean readable code your final example is much better.
If you're catching exceptions in the calling method ( Ithink) you should only catch exceptions which you expect. If the exception is a problem for Load(), then throw a new exception to the calling method, with better information about the exception.
Excellent! You are definitely on the right track. The previous implementation doing nothing other than re-throwing exceptions which is unnecessary. You should only handle specific exceptions that you are anticipating in the business layer, otherwise let them naturally go up the call stack up to the UI layer.
As best practice, only re-throw exceptions when you want to add some additional debug information, in which case you will need to define a custom exception
The exception will be caught by the catch statement but since it has a throw statement, it'll throw the exception back out. This has the same effect as if you didn't have a try/catch at all, so your colleague is right in suggesting leaving it out.
There isn't much of a point to adding exception-handling code if you don't actually handle the exception in any way.
I agree with your colleague, you should only catch exceptions that you know need to be caught. I typically leave out any try catch blocks unless I know exactly why I need it in a particular situation. This is because you tend to hide the real bugs in your code if you just put try catch block around everything. Leave the error handling off until you absolutely need it - start off with a single global error handler at the highest point in the application - if this is asp.net you can hook the application error event and log errors there, but my point is don't add try catch blocks unless you know why your adding them and write code that handles error cases not traps them.
Enjoy!

Can't declare unused exception variable when using catch-all pattern

what is a best practice in cases such as this one:
try
{
// do something
}
catch (SpecificException ex)
{
Response.Redirect("~/InformUserAboutAn/InternalException/");
}
the warning i get is that ex is never used.
however all i need here is to inform the user, so i don't have a need for it.
do i just do:
try
{
// do something
}
catch
{
Response.Redirect("~/InformUserAboutAn/InternalException/");
}
somehow i don't like that, seems strange!!? any tips? best practices?
what would be the way to handle this.
thnx
You just don't declare the variable:
try
{
// do something
}
catch (SpecificException)
{
Response.Redirect("~/InformUserAboutAn/InternalException/");
}
This is a moot point when catching System.Exception (in your original example, which is not exactly the same as an empty catch -- an empty catch will also catch COM exceptions, for instance), but this is the correct construct to use.
If you run your code through other analysis engines (Gendarme, for instance), you will also be warned that catching a plain Exception is poor practice because it can mask other exceptions besides what you really wanted to catch. That's bitten me a few times while maintaining legacy code -- we were catching and ignoring an Exception on a file delete (or something like that), but the main logic wasn't working correctly. We should have been only catching an IOException, but we were catching and discarding the NullReferenceException that was causing the failure.
That's not to say you never should catch Exception; just rarely.
If you don't need Exception's variable to get some information from it, don't declare it
try { }
catch ( )
is equal to
try { }
catch (Exception) { }
Use this
try { }
catch (Exception ex) { var m = ex.Message; }
if you need some information to gather.
Use this
try { }
catch (FooException) { }
catch (BarException) { }
if you need to catch only specific types of exceptions, i.e. SomeAnotherException will not be caught.
It would be better if you just let the exception bubble all the way up and use an application wide exception handler or something like ELMAH. Usually you'll want to log the exception or something so there's a record of stuff failing.
Any reason why you wouldn't let unhandled exceptions simply throw and use the Application Level error handling built into ASP.NET? See How to: Handle Application-Level Errors for more details.
I usually declare it and suffer with the warning since it can be very useful to be able to look at the exception details while debugging.
There are two reasons to declare an exception variable in a catch block. To catch only specific exception types or to do something with the exception info. In your case you are doing neither so t serves no purpose.

Thoughts on try-catch blocks

What are your thoughts on code that looks like this:
public void doSomething()
{
try
{
// actual code goes here
}
catch (Exception ex)
{
throw;
}
}
The problem I see is the actual error is not handled, just throwing the exception in a different place. I find it more difficult to debug because i don't get a line number where the actual problem is.
So my question is why would this be good?
---- EDIT ----
From the answers it looks like most people are saying it's pointless to do this with no custom or specific exceptions being caught. That's what i wanted comments on, when no specific exception is being caught. I can see the point of actually doing something with a caught exception, just not the way this code is.
Depending on what quality you are looking at it is not throwing the exception in a different place. "throw" without a target rethrows the exception which is very different from throwing an exception. Primarily a rethrow does not reset the stack trace.
In this particular sample, the catch is pointless because it doesn't do anything. The exception is happily rethrown and it's almost as if the try/catch didn't exist.
I think the construction should be used for handling the exceptions you know you will be throwing inside your code; if other exception is raised, then just rethrow.
Take into account that
throw;
is different than
throw ex;
throw ex will truncate the stack to the new point of throwing, losing valuable info about the exception.
public void doSomething()
{
try
{
// actual code goes here
}
catch (EspecificException ex)
{
HandleException(ex);
}
catch (Exception ex)
{
throw;
}
}
It wouldn't be, ideally the catch block would do some handling, and then rethrow, e.g.,
try
{
//do something
}
catch (Exception ex)
{
DoSomething(ex); //handle the exception
throw;
}
Of course the re-throw will be useful if you want to do some further handling in the upper tiers of the code.
Doing something like that is fairly meaningless, and in general I try not to go down the road of doing meaningless things ;)
For the most part, I believe in catching specific types of exceptions that you know how to handle, even if that only means creating your own exception with more information and using the caught exception as the InnerException.
Sometimes this is appropriate - when you're going to handle the exception higher up in the call stack. However, you'd need to do something in that catch block other than just re-throw for it to make sense, e.g. log the error:
public void doSomething()
{
try
{
// actual code goes here
}
catch (Exception ex)
{
LogException (ex); // Log error...
throw;
}
}
I don't think just rethrowing the error would be useful. Unless you don't really care about the error in the first place.
I think it would be better to actually do something in the catch.
You can check the MSDN Exception Handling Guide.
I've seen instances where generic exceptions are caught like this and then re-packed in a custom Exception Object.
The difference between that and what you're saying is that those custom Exception objects hold MORE information about the actual exception that happened, not less.
Well for starters I'd simply do
catch
{
throw;
}
but basically if you were trapping multiple types of exceptions you may want to handle some locally and others back up the stack.
e.g.
catch(SQLException sex) //haha
{
DoStuff(sex);
}
catch
{
throw;
}
Depends on what you mean by "looks like this", and if there is nothing else in the catch block but a rethrow... if that's the case the try catch is pointless, except, as you say, to obfuscate where the exception occurred. But if you need to do something right there, where the error occurred, but wish to handle the exception furthur up the stack, this might be appropriate. But then, the catch would be for the specific exception you are handl;ing, not for any Exception
Generally having exception handling blocks that don't do anything isn't good at all, for the simple reason that it prevents the .Net Virtual Machine from inlining your methods when performance optimising your code.
For a full article on why see "Release IS NOT Debug: 64bit Optimizations and C# Method Inlining in Release Build Call Stacks" by Scott Hanselman

Categories

Resources