I have followed this way of handling exception in my application. But my lead said I am doing it wrong. I am simply wrapping and rethrowing the same exception, which will impact performance.
What is wrong with my approach? Does anyone have any suggestions on how I can log and handle the exception here?
public class BusinessRepository : IBusinessRepo
{
public List<Employee> GetEmployees()
{
try
{
//do some DB operations
}
catch (SQLException sqlex)
{
Logger.Log("Exception detail with full stack trace");
throw new DALException(sqlex, "Error in data access layer");
}
}
}
public class BusinessLayerClass : IBusinessLayer
{
private readonly IBusinessRepo Repo;
public BusinessLayerClass(IBusinessRepo rep)
{
Repo = rep;
}
public List<Employee> GetEmployees()
{
try
{
List<Employee> emps= return Repo.GetEmployees();
}
catch (DALException dex)
{
//do nothin as it got already logged
throw;
}
catch (Exception ex)
{
Logger.Log(ex, "Business layer ex");
throw new BusinessLayerEx(ex);
}
}
}
public class HomeController : Controller
{
public ActionResult Index()
{
try
{
List < Employee >= BusinessLayerClass.GetEmployees();
}
catch (DALException)
{
//show error msg to user
}
catch (BusinessLayerEx)
{
//show error msg to user
}
catch (Exception ex)
{
Logger.Log();
//show error msg to user
}
return View(emps);
}
}
Do i follow right way of bubbling and handling and logging shown above?
I'm inclined to agree with your way of doing this, as long as two conditions are met:
Your Logger.Log statements log something more meaningful/useful than what you've indicated here (I'm guessing your code here is just a sample message indicating the error is logged). If it provides information you can use to track down the cause of the exception, good.
Your //show error msg to user comments mean that in that location, you render a nice view explaining that an error has occured, and you aren't just showing a default exception screen/strack trace.
As far as your throw; when you catch the DALException you just threw: that's fine. Your goal here seems to be to catch any exception coming out of the previous layer and log it, throwing your own exception afterwards. Since DALException will only be thrown if you've already logged another error and thrown it yourself, it's perfectly fine to let it bubble up past this level.
The general rule of thumb for exceptions is do not catch them unless you can "do something about it", i.e. add value. Ideally this would be some kind of graceful recovery to the point that the user never knows there was a hiccup, but at the very minimum this would include logging the exception -- which you are doing.
Do not catch an exception only to immediately re-throw it. That adds no value. (An exception to this might be if you need to change the type of exception to something more informative/appropriate to the context).
Throwing and catching exceptions is expensive compared to any normal return mechanism, but it's kind of besides the point - we're not supposed to use exceptions as normal control-flow mechanisms, but to handle exceptional things.
Exception handling can be quite challenging technically. After all, most of the time we exactly don't expect them. But what can make it near-impossible to get exception handling "right" is when the team or project simply doesn't have any kind of strategy for error handling. In an ideal world, we would know at the outset exactly what sort of error conditions we need to cope with, and we'd design the whole application with those in mind (along with the gazillion other constraints we also need to keep in mind, from code readability to performance).
I'd say if your lead says "this is wrong" then it's fair to ask "what's our error-handling strategy?". If you don't even know what purpose your code is supposed to fulfill, how can you possibly deliver great code?
There's nothing wrong with your approach but I don't see that your custom exceptions add much value. A example of how wrapping an exception in the DAL could add value is if you wrapped specific SQL exceptions, such as unique key violation, in a custom exception so that your UI could present a meaningful error message.
As for performance, it doesn't really matter anyway because something very bad has already happened.
Related
According to this answer: https://stackoverflow.com/a/1722991/680026
you should only use try-catch if you really do something there besides logging:
Don't catch an exception if you're only going to log the exception and
throw it up the stack. It serves no meaning and clutters code.
But what about logging information that are not available at the higher level?
eg:
private void AddSomethingToTable(string tablename, string fieldname) {
try {
InsertFieldToTable(tablename, fieldname);
} catch (Exception ex) {
log.ErrorFormat("Could not insert field '{0}' into table '{1}'", fieldname, tablename);
throw;
}
}
private void main() {
try {
AddSomethingToTable("users","firstname");
AddSomethingToTable("users","lastname");
AddSomethingToTable("users","age");
} catch (Exception ex) {
MessageToUser("Sorry. Saving did not work.",ex);
}
}
As you can see: In my (completely made up) example I log the information about the field that did cause the error. This could be some good information to start finding the error.
So even though I only logged the error, this information could be crucial and be lost outside that method.
Is this a valid use of try-catch here or are there other suggested ways to log that? (I don't think that just always logging this info (regardless if an error occurred or not) would be a valid solution)
I think you answered your own question with
But what about logging information that are not available at a higher instance
and
this information could be crucial and be lost outside that method
I dislike hard and fast "always do X and never Y", because there are times where it is necessary to go against so-called "best practice" in order to do what is best for your application.
If logging the information is necessary to fix the issue, and you lose this information if you don't log it immediately, then log the information.
There is nothing wrong in what you are trying to do. The idea of the other question/answer was that it is better to log the error at the place where you really handle it. In .NET every exception contains a stack trace. This means that upper layer can report location in the code that has generated this error. Doing that in one place instead of many is way more meaningful. This was their idea.
From your linked quesion:
The basic rule of thumb for catching exceptions is to catch exceptions if and only if you have a meaningful way of handling them.
I put emphasis on "The basic rule of thumb" as it's not a law. It's a best practice. i.e. follow it until you have a good motivation to not do so.
If you catch exceptions to include information you probably should throw a new meaningful exception with more context information. something like:
try
{
//kldfsdölsdöls
}
catch (Exception ex)
{
throw new MoreDetailedException("Text with context data", ex);
}
That way you'll get all context information for each stack level collected into the same exception (since you included the inner exception in it). Thus the log entry in the top level will contain ALL information in the same line.
But what about logging information that are not available at a higher
instance?
You can pass those information back to caller while re-throwing the exception
private void AddSomethingToTable(string tablename, string fieldname) {
try {
InsertFieldToTable(tablename, fieldname);
} catch (Exception ex) {
string str = string.Format("Could not insert field '{0}' into table '{1}'", fieldname, tablename);
throw new Exception(str, ex);
}
}
We use the Try Catch block in a similar way you have suggested and it works well for us.
We have implemented ELMAH https://code.google.com/p/elmah/ which is great for logging untrapped errors. With a line of code in the Try Catch block you can also write trapped exceptions into the log.
Catch ex As Exception
Elmah.ErrorSignal.FromCurrentContext.Raise(ex)
Return False
End Try
The error is handled (the relevant function returned false) and user doesn’t get the Yellow Screen of Death, and we can look up full details of any errors in the log.
Just a thing I've been thinking of for a while. Do I need to handle KeyNotFoundException by catching that specific exception or can I just use a "blank" catch like this:
try
{
//Code goes here
}
catch
{
}
Or do I have to do it like this:
try
{
//Code goes here
}
catch(Exception ex)
{
}
Or do I have to do it like this:
try
{
//Code goes here
}
catch(KeyNotFoundException ex)
{
}
The reason why I ask is that when I look at crash count at App Hub I have a lot of crashes related to "KeyNotFoundException" but I never experience any crashes in my app. Could this be the problem, that I don't catch the specific exception and that App Hub crash statistics classifies it as a crash even if the exception is handled?
EDIT:
Here are some screenshots of the App Hub crash statistics (Stack Trace). Does anyone know ehat in detail it means? It has to do with my background agent and that might be the reason for why I never experience any crashes in my app:
No, the marketplace is counting only unhandled exceptions, so your app does crash.
An empty catch or catching Exceptions are the most general catches (Every exception is derived from the Exception base class, so you're catching everything.), the critical code is somewhere you don't use try-catch. Based on the exception you should check your dictionaries and think about what are the conditions which can cause error.
Generally a good practice is to check the correctness of parameters in your public methods so if any problem occurs you can provide yourself more helpful error messages, for example:
public User GetUser(string username)
{
if (String.IsNullOrEmpty(username))
throw ArgumentNullException("username");
return this.users[username];
}
In this case if things goes wrong you will see that you used a null for username, otherwise you would see a KeyNotFoundException. Hope this helps, good luck!
You can use a base exception to catch a more derived exception, so Exception will catch KeyNotFoundException because the latter inherits the former. So strictly speaking, if you want to catch "any" exception, catch (Exception) will suffice.
However, you should only catch exceptions if you can handle them in some meaningful manner. Though I'm not sure how this mindset stacks up against WP development.
As for your underlying problem, I've no idea. Does the App Hub not provide any details around the crash such as stack traces?
Your best bet is to leave the template code in place that registers for the unhandled exceptions event and put some logging into your application to record as much detail as you can about the state of the app during the crash.
No, you do not have to catch each specific exception type in a try / catch block, see the C# language reference.
However, rather than wrapping all your code in try / catch blocks, you probably want to add exception handling logic and logging into a handler for the Application.UnhandledException event. See this excellent blog post for an example of how to handle this event.
If you are interested in a specific exception, such as KeyNotFoundException in a particular part of the code then you catch it like this
try
{
//Code goes here
}
catch(KeyNotFoundException ex)
{
}
If you want to catch a specific exception and some undefined one you do something like this
try
{
//Code goes here
}
catch(KeyNotFoundException ex)
{
}
catch(Exception ex)
{
}
If you want to make sure your application doesn't crash use Collin's example with the Application.UnhandledException event.
You can catch all exceptions by catching the base class, but whether you want to depends on what your trying to achieve.
Generally speaking, you should only catch an exception at a level at which you have the knowledge to decide what should be done about the error, ie roll back some action, or display a message to the user. It is often the case that at a certain level it makes sense to catch a specific exception type, as that level of code understands what that means, but it may not make sense to catch all.
Avoid catching everything too soon, exceptions exist to tell you somethings wrong, blanket catching ignores that and can mean your program keeps running, but starts behaving wrong, possibly corrupting data. Its often better to "fail early and fail fast" when receiving unexpected exceptions.
As others have said - No - you dont need to catch the specific exception, catching Exception or just catch will prevent the exception from bubbling up.
However you should just catch specific exceptions where possible to make your code more explicit in what it is doing. Better again test for correctness before the potential error condition - again this is covered in other posts.
For your specific problem the link you posted seems to indicate that it is a problem with reading values from the isolated storage (IsolatedStorage.get_Item) - so wherever you access IsolatedStorage during from the ScheduledTaskAgent invocation you need to ensure the item exists before getting it. Perhaps there are some config settings missing or something?
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Catching specific vs. generic exceptions in c#
Here's an example method
private static void outputDictionaryContentsByDescending(Dictionary<string, int> list)
{
try
{
//Outputs entire list in descending order
foreach (KeyValuePair<string, int> pair in list.OrderByDescending(key => key.Value))
{
Console.WriteLine("{0}, {1}", pair.Key, pair.Value);
}
}
catch (Exception e)
{
MessageBox.Show(e.Message, "Error detected", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
I would like to know what exception clause to use apart from just Exception and if there is an advantage in using more specific catch clauses.
Edit: O.k thanks everyone
Catching individual types of Exceptions in your statement will allow you to handle each in a different way.
A blanket rule for Exception may be useful for logging and rethrowing Exceptions, but isn't the best for actually handling Exceptions that you may be able to recover from.
try
{
// open a file specified by the user
}
catch(FileNotFoundException ex)
{
// notify user and re-prompt for file
}
catch(UnauthorizedAccessException ex)
{
// inform user they don't have access, either re-prompt or close dialog
}
catch(Exception ex)
{
Logger.LogException(ex);
throw;
}
You should only really catch exceptions that you are expecting that code may throw. That way, if it throws something you didn't expect, it may either be something critical; something that should bubble up the call stack and possibly crash the application; or something you have not thought of.
For example, you may wish to handle IOExceptions thrown by I/O code so that you can relay the problem back to the user. However, the same operations may throw something more critical such as an AccessViolationException. In this case, you might want the program to terminate, or handle the problem in a different way.
Generic exception handling should only really be used in cases where you do not care what error occurred, and subsequently don't want it affecting the rest of your process.
The only potential cause for an exception that I see in your example is if list is null. OrderByDescending() should return an empty IEnumerable<> rather than a null reference.
If I read that correctly, it might make more sense to catch NullReferenceException:
try
{
...
} catch (NullReferenceException exception)
{
MessageBox.Show(...);
}
However, this really depends on the needs of your application. If your intention is just to alert the user or to log all exceptions, catching the Exception class is fine. If you need special handling for different types of exceptions - such as sending an email alert instead of just logging the message - then it makes sense to use specific exception types:
try
{
}
catch(NullReferenceException e)
{
//...
}
catch(StackOverflowException e)
{
//...
}
catch(Exception e)
{
/// generic exception handler
}
Which exception to use really depends on the code in the try block. In general you want to catch exceptions that you can do something with and let exceptions you have no power over move to high levels of your code where you can perform some action that makes since. One of the most common mistakes I see people make is attempting to catch errors that they have no ability to handle.
for example
Void ChoseFile()
{
try
{
string FileName = GetInputFile()
}
catch( InvalidFileSelectedException ex)
{
//In this case we have some application specific exception
//There may be a business logic failure we have some ability
//to infomr the user or do an action that makes sense
}
catch(FileNotFoundException exfilenot found)
{
//In this case we can do somthing different the the above
}
catch(Exception )
{
//Normal I would not use this case we have an error we don't know what to do
//with. We may not have a usefull action. At best we can log this exception
// and rethrow it to a higher level of the application that can inform the user
// fail the attempted action. Catching here would only suppress the failure.
}
}
You should always catch exceptions with an as specific class as possible.
If you know what to do if a file is locked, but you regard all other errors as unexpected and impossible to handle, you should catch System.IO.IOException and deal with the error. You should only catch Exception (or just catch {) for gracefully exiting.
Since you are dealing with a Dictionary.. then you want to look at these 2 exceptions
The key of keyValuePair is a null reference (Nothing in Visual Basic).
ArgumentException An element with the same key already exists in the Dictionary(TKey, TValue).
KekValuePair Exception
This is taken from the MSDN site
Use the exception type that you might expect but still not be able to prevent and that you can adequately handle. Let anything else bubble up to somewhere that might expect it or can handle it.
In your case here, I might expect that I would run into a NullReferenceException if the dictionary is null. But I would not catch it. This is something I can validate against instead
if (dictionary != null)
So there is no reason to allow an exception to even happen. Never use exceptions for control flow, and validate against known causes.
Some classes/methods will throw different exceptions, depending on the error. For example, you might be using the File class to write data to a file. You could write multiple Catch statements for the exception types you could recover from, and a generic Exception catch to log and bubble up anything that can't be recovered from.
By using Exception you catch all exceptions. Of you use IOException or StackOverflowException you'll only catch errors of that type.
a StackOverflowException catched by a Exception still hold the same message, stack trace etc.
Exception handling philosophy
I am sure you can find many other philosophies
Code defensively. Catching exceptions is more expensive than preventing the error in the first place.
Don't catch an exception and bury it by not handling it. You can spend many hours trying to find an error that has been suppressed.
Do log errors that you catch.
This helps in analyzing the problem. You can check to see if more than one user is having the same problem
I prefer a database for logging, but a flat file, or the event log are also suitable.
The database solution is easiest to analyze but may introduce additional errors.
If the error is due to bad data entered by the user, inform the user of the problem and allow them to retry.
Always allow an escape route if they cannot fix the problem.
Catch the error as close to the source as possible
This could be a database procedure, a method in a data access layer (DAL) or some other location.
Handling the exception is different than catching it. You may need to rethrow the exception so that it can be handled higher up the stack or in the UI.
Rethrowing the exception can be done in at least two ways.
throw by itself does not alter the stack.
throw ex does alter or add to the stack with no benefit.
Sometimes it is best not to catch an exception, but rather let it bubble up.
If you are writing services (web or windows) that do not have a user interface (UI) then you should always log the error.
Again, this is so that someone can analyze the log or database file to determine what is happening.
You always want someone to know that an error has occurred.
Having a lot of catch statements for a try block can make your code more difficult to maintain, especially if the logic in your catch blocks is complex.
Instead, code defensively.
Remember that you can have try catch blocks within catch blocks.
Also, don't forget to use the finally block where appropriate.
For example, closing database connections, or file handles, etc.
HTH
Harv
When the WCF service is turned off, I'm gonna catch this exception like this.
public List<ProjektyEntity> GetProjekty()
{
try
{
return this.channel.GetProjekty();
}
catch (EndpointNotFoundException exception)
{
//what to do at this point ?
}
}
But i don't know what to do in the catch block.I can return only an object of type List<ProjektyEntity> I'd like to write a message to the user,something like "The service is turned off" My presentation layer is ASP.NET MVC. Is there any strategy for this kind of situations?
There's a simple rule: If you don't know how to handle an exception, don't catch it.
Catching it and retuning null or an empty list would be about the worst thing you can do because it will be hard to debug where the error is coming from, or even that an error occured at all. If you do this you will have developers pulling their hair out.
Catching an exception and rethrowing it as throw e; is also bad because you lose the original stack. Rethrowing using throw; is OK sometimes if you have special clean up you need to do only if there is an error. Usually this is not the case. If you have cleanup that should be done whether or not there was an error, it belongs in the finally clause.
So in general unless there is something sensible you can do to recover from the error, just let the exception propogate to the caller. This is how exceptions are designed to work.
There are a few times when you might want to catch an exception to add more information (e.g. for logging), in which case you should ensure that you use an InnerException to avoid losing the original information:
try
{
foo(bar);
}
catch (Exception e)
{
throw new FooException("Foo failed for " + bar.ToString(), e);
}
but in general it's best not to do this unless you have a very good reason. Doing this prevents your users from catching a specific type of exception - they will catch your exception and then they need to switch on the type of the InnerException. Not fun. Just let the caller see the original exception.
I can see a few options here. Determining which is appropriate is probably dependent on the application.
Display an error and return null. Clean and simple, but inflexible. May not be what you want in every case where this function is used.
Don't catch it, let the caller catch this exception. It may be easier to determine the appropriate response from the calling function (ie. display a message / retry in a few seconds / etc)
Catch it and throw a new ServiceNotAvailableException Slightly more complex than option two, but will make your code clearer.
Just return null. Probably the least desirable approach unless this service being down is common and no big deal.
It seems to me that you should not catch this exception at that layer; you should let the exception propagate up to the controller layer and let the controller layer displays the message.
There are several approaches:
1) Don't catch the exception, and let the caller (user interface layer) handle it
2) Catch the exception so you can do anything you need to do, and then re-throw it
catch (EndpointNotFoundException exception)
{
CleanUpMyOwnState();
throw; // Pass the exception on the to the caller to handle
}
3) Convert the exception into another type (to make it easier to handle in the caller):
catch (EndpointNotFoundException exception)
{
CleanUpMyOwnState();
throw new InvalidOperationException("Endpoint was not found", exception);
}
4) catch it, and then return an error code (e.g null), so the caller doesn't need to use exception handling to deal with it (but there's no real advantage to doing this)
5) Catch the exception and report the error to the user yourself. This is probably a bad idea - you should keep all error reporting in your UI layer.
The exception is not supposed to be caught and handled in this context. It needs to be handled at much higher level having access to any console in general.
The best you can do here is just log the exception with necessary details and rethrow properly.
Create an exception object with enough debugging details and throw it to calling method
public List<ProjektyEntity> GetProjekty()
{
try
{
return this.channel.GetProjekty();
}
catch (EndpointNotFoundException exception)
{
'Write here Some Clean Up Codes
' Log it somewhere on your server so that you can fix the error
}
}
Should I catch exceptions for logging purposes?
public foo(..)
{
try
{
...
} catch (Exception ex) {
Logger.Error(ex);
throw;
}
}
If I have this in place in each of my layers (DataAccess, Business and WebService) it means the exception is logged several times.
Does it make sense to do so if my layers are in separate projects and only the public interfaces have try/catch in them?
Why? Why not? Is there a different approach I could use?
Definitely not. You should find the correct place to handle the exception (actually do something, like catch-and-not-rethrow), and then log it. You can and should include the entire stack trace of course, but following your suggestion would litter the code with try-catch blocks.
Unless you are going to change the exception, you should only log at the level where you are going to handle the error and not rethrow it. Otherwise your log just has a bunch of "noise", 3 or more of the same message logged, once at each layer.
My best practice is:
Only try/catch in public methods (in general; obviously if you are trapping for a specific error you would check for it there)
Only log in the UI layer right before suppressing the error and redirecting to an error page/form.
The general rule of thumb is that you only catch an exception if you can actually do something about it. So at the Business or Data layer, you would only catch the exception in situation's like this:
try
{
this.Persist(trans);
}
catch(Exception ex)
{
trans.Rollback();
throw;
}
My Business/Data Layer attempts to save the data - if an exception is generated, any transactions are rolled back and the exception is sent to the UI layer.
At the UI layer, you can implement a common exception handler:
Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
Which then handles all exceptions. It might log the exception and then display a user friendly response:
static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
LogException(e.Exception);
}
static void LogException(Exception ex)
{
YYYExceptionHandling.HandleException(ex,
YYYExceptionHandling.ExceptionPolicyType.YYY_Policy,
YYYExceptionHandling.ExceptionPriority.Medium,
"An error has occurred, please contact Administrator");
}
In the actual UI code, you can catch individual exception's if you are going to do something different - such as display a different friendly message or modify the screen, etc.
Also, just as a reminder, always try to handle errors - for example divide by 0 - rather than throw an exception.
It's good practice is to translate the exceptions. Don't just log them. If you want to know the specific reason an exception was thrown, throw specific exceptions:
public void connect() throws ConnectionException {
try {
File conf = new File("blabla");
...
} catch (FileNotFoundException ex) {
LOGGER.error("log message", ex);
throw new ConnectionException("The configuration file was not found", ex);
}
}
Use your own exceptions to wrap inbuild exception. This way you can distinct between known and unknown errors when catching exception. This is usefull if you have a method that calls other methods that are likely throwing excpetions to react upon expected and unexpected failures
you may want to lookup standard exception handling styles, but my understanding is this: handle exceptions at the level where you can add extra detail to the exception, or at the level where you will present the exception to the user.
in your example you are doing nothing but catching the exception, logging it, and throwing it again.. why not just catch it at the highest level with one try/catch instead of inside every method if all you are doing is logging it?
i would only handle it at that tier if you were going to add some useful information to the exception before throwing it again - wrap the exception in a new exception you create that has useful information beyond the low level exception text which usually means little to anyone without some context..
Sometimes you need to log data which is not available where the exception is handled. In that case, it is appropriate to log just to get that information out.
For example (Java pseudocode):
public void methodWithDynamicallyGeneratedSQL() throws SQLException {
String sql = ...; // Generate some SQL
try {
... // Try running the query
}
catch (SQLException ex) {
// Don't bother to log the stack trace, that will
// be printed when the exception is handled for real
logger.error(ex.toString()+"For SQL: '"+sql+"'");
throw; // Handle the exception long after the SQL is gone
}
}
This is similar to retroactive logging (my terminology), where you buffer a log of events but don't write them unless there's a trigger event, such as an exception being thrown.
If you're required to log all exceptions, then it's a fantastic idea. That said, logging all exceptions without another reason isn't such a good idea.
You may want to log at the highest level, which is usually your UI or web service code. Logging multiple times is sort of a waste. Also, you want to know the whole story when you are looking at the log.
In one of our applications, all of our pages are derived from a BasePage object, and this object handles the exception handling and error logging.
If that's the only thing it does, i think is better to remove the try/catch's from those classes and let the exception be raised to the class that is responsible on handling them. That way you get only one log per exception giving you more clear logs and even you can log the stacktrace so you wont miss from where the exception was originated.
My method is to log the exceptions only in the handler. The 'real' handler so to speak. Otherwise the log will be very hard to read and the code less structured.
It depends on the Exception: if this actually should not happen, I definitely would log it. On the other way: if you expect this Exception you should think about the design of the application.
Either way: you should at least try to specify the Exception you want to rethrow, catch or log.
public foo(..)
{
try
{
...
}
catch (NullReferenceException ex) {
DoSmth(e);
}
catch (ArgumentExcetion ex) {
DoSmth(e);
}
catch (Exception ex) {
DoSmth(e);
}
}
You will want to log at a tier boundary. For example, if your business tier can be deployed on a physically separate machine in an n-tier application, then it makes sense to log and throw the error in this way.
In this way you have a log of exceptions on the server and don't need to go poking around client machines to find out what happened.
I use this pattern in business tiers of applications that use Remoting or ASMX web services. With WCF you can intercept and log an exception using an IErrorHandler attached to your ChannelDispatcher (another subject entirely) - so you don't need the try/catch/throw pattern.
You need to develop a strategy for handling exceptions. I don't recommend the catch and rethrow. In addition to the superfluous log entries it makes the code harder to read.
Consider writing to the log in the constructor for the exception. This reserves the try/catch for exceptions that you want to recover from; making the code easier to read. To deal with unexpected or unrecoverable exceptions, you may want a try/catch near the outermost layer of the program to log diagnostic information.
BTW, if this is C++ your catch block is creating a copy of the exception object which can be a potential source of additional problems. Try catching a reference to the exception type:
catch (const Exception& ex) { ... }
This Software Engineering Radio podcast is a very good reference for best practices in error handling. There are actually 2 lectures.
It's bad practice in general, unless you need to log for very specific reasons.
With respect in general log exception, it should be handled in root exception handler.