I'm using PDO to connect to a mysql database. I'm confused as to where I should be using try catch blocks if I set the error attribute like so:
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Right now I have my connection info (username, pass, etc) and the line above in a separate file that I will include in my main files. These (connection info and the line above) are stored in a try-catch block.
In my main files, I include this file. Do I need try-catch blocks in my main files too (around pdo related stuff)? (They are where I create and execute queries).
As with all exceptions, you'll need to handle them anytime they're not handled and at a place it makes sense to handle them. For each method that may throw, ask yourself where could it conceivably be handled properly? It may not make sense to catch exceptions right when the PDO functions that may throw them are called, but at a higher level. (For example, it doesn't make sense to handle a PDOException at the point a new PDO object is created, as the code that follows will depend on having a valid PDO object; instead, it must be handled at a point that can either attempt to recover from the exception or fail gracefully.) This is the reason for exceptions: errors may be detected at a lower level, where there may not be sufficient information to deal with the error. So, the code throws an exception to somewhere higher that can deal with the error.
In a well designed project, datastore access is sequestered away into a module, so most of the rest of the code is unaffected by the exact nature of the datastore. In architectures that have this separation (such as multi-tiered or MVC), the datastore exceptions would be handled in the data access layer, though "handling" may mean throwing a different type of exception.
It helps to think about exception handling strategies:
retry by fixing something and trying the failed operation again
retry by restarting an operation
continuing on with the process and retry the operation at a later time (don't just continue on and ignore the exception)
throwing an exception (which could be the same exception) to a higher level
retry by display an error message to the user, giving them a chance to fix something and (if so) retry the failed operation
display an error message to the user and end (only don't use or die when outputting HTML; invalid HTML isn't graceful).
See also: "Exception-handling antipatterns".
If you're asking whether setting the error mode to PDO::ERRMODE_EXCEPTION will cause exceptions to be caught, then no; just the opposite, in fact. Only catch blocks can handle exceptions.
Related
My idea of handling exceptions is as follows.
When an unhandled exception occurs, I want to save a dump with full memory, including local variables available at the line where the exception happened. Then I can analyze that dump and either prevent the exception from happening again or handle it with try...catch.
I almost achieved my goal by simply handling AppDomain.CurrentDomain.UnhandledException event. It fires every time an unhandled exception occurs and its call stack includes the line of the exception, so after saving a dump I have all the data I need including local variables.
However, that solution doesn't work with TPL. After encountering an unhandled exception a task terminates and only then allows me to access the exception through various means (checking Task.Exception, handling TaskScheduler.UnobservedTaskException event, using continuation with TaskContinuationOptions.OnlyOnFaulted, using Task.Wait() or await...). Those methods obviously do not allow me to include local variables from within a task, since the task itself already terminated.
Is there something I can do to catch unhandled exceptions occuring within tasks before those tasks are terminated? And if so, can I then save a dump including local variables from within those tasks?
Here are some ideas for a solution I came up with:
I can use AppDomain.CurrentDomain.FirstChanceException, but from within that event I can't check whether an exception will be handled in a catch block or not. And obviously I don't want to save a dump for some exception that will be later handled in a catch block. But, since it looks like the event handles only one AppDomain, I could theoretically run all the code placed within try...catch blocks from some other AppDomain. But I have no idea how to achieve that nor whether it would actually work, not to mention possible drawbacks.
Is it possible to write an alternative to try...catch in IL, which won't leave the try block after encountering an exception, thus allowing access to local variables?
I can simply use try...catch and declare my local variables before the try block, but I treat that solution as the last resort, since it's ugly.
It is quite tiresome writing try/catches in every method block.
Apart from AOP, is there any way to avoid this and catch all exceptions? Would it be enough to just catch them at the global error handler level (e.g. as in ASP.NET).
Thanks
The best advice I've heard on the subject (somewhere on SO, actually) was "only catch an exception if you're going to handle it." That is, it only makes sense to use a catch block in that method if that method has the means of handling the exception. For example, if the method should for some reason always return a value, and the exception is either silently logged or somehow indicated in the value (such as an error message attached to some custom DTO or something). There's nothing wrong with bubbling the exception upward in the stack and assuming the caller will handle it.
That's not to say, of course, that it shouldn't be handled at all. As you suggest, the last line of defense should always be the global exception handling for the application. All fails should be handled gracefully, but they should more importantly be handled only by the class/method that is supposed to handle them, which in many cases is not the method from which the exception originated. For example, in a simple forms over data web app, the data access doesn't necessarily need to handle the exception. It can add information to it if pertinent, but for such a simple app the global error handler can take care of logging and presenting an error message.
It should also be noted (I'm assuming you're talking about .NET here) that a try block need not always be accompanied by a catch block. You can try{}finally{} to take care of cleaning up after an exception (such as gracefully closing an external resource) without bothering to catch the exception and instead let it bubble up accordingly.
I agree with David. Here's my basic set of rules, or ... like the pirate code, guidelines ...
There should always be one global exception handler to catch runtimes and anything else that the classes cannot handle.
Try/catch should only be implemented when you can actually do something about the exception. And No, logging the exception is not doing something about it.
Adding a throws or Throwing a Exception or RuntimeException should be avoided. If you have a wide or large number of exceptions to deal with, create a new exception class to wrap them. Exception is too general and creates problems for other developers.
Try/catch blocks are expensive, do don't put them in unless necessary.
Never, and I mean NEVER !!! use try/catch for logic flow.
I've found it helpful to think of your code as having three layers, and using an exception strategy appropriate to each layer. I wrote up the details in Exceptions in the Rainforest.
I read several posts on exception handling/rethrowing exceptions on here (by looking at the highest voted threads), but I am slightly confused:
-Why would you not want the immediate catch block to handle an exception but rather something above it?
-Also, I read quite frequently that you should only handle exceptions which you can "handle". Does that mean actually doing something about it, such as retrying the operation?
You might want to catch an exception (e.g. file not found) and do some processing - e.g. if you open two files and the second file is missing, you will want to close the first file again before you continue, so that it isn't left open.
You might then want to tell the caller that an error occurred, so you re-throw the same exception or throw a new exception, describing the problem.
In some cases, if you get an exception, your code has no way of knowing if it is an error or not (e.g. if you are asked to load an XML file, but you get a File Not Found exception, is that an error, or should you return a blank XMl result?). In these cases you either want to re-throw the exception, or not handle it all all, and let the calling code decide how to deal with the problem.
Your second point is the answer to the first. Sometimes the lower-level functionality does not know enough about the context of the application to know what the right action should be. For example, if opening a file for reading fails because there is no file of that name, then the application might want to ask for a different file, or abort the whole operation, or whatever. At some level, some part of the application will take the responsibility to do the right thing, unless of course just having the program crash is an acceptable action to take.
Answering to your second question - you need to handle the exception in the immediate block only if can do anything about it: for example close connection to db, close streams, retry or retry with different params, log exception (if there will not be an exception generic handler on the higher levels). Probably only immediate block of code knows such details and can handle them. Calling blocks need to know that the error occurred they might know better what to do with exception.
For example immediate block works with a file. A caller might try to open a file from different locations(In the process of "probing") and ignore several errors as long as at least one succeeds. Another part of code might consider the very first failed attempt as an error. Caller block might chose to notify the user that an error is occurred, probably let her/him know some helpful info on how to fix the problem. Also it is nice to provide the means to notify support of the problem – some kind of dialog allowing user to ask for help, describe problem and send a message. In this message you might attach logs, some info about the environment like OS, versions of frameworks, programs, browser capabilities whatever you need to diagnose the problem (if user permits you to do so).
An exception is "handled" if the method which caught it can satisfy its construct. For example, the contract for a routine OpenRecentDocument which is called when the user selects an item from the "recent files" menu might specify that it must either (1) successfully open a document window, or (2) try unsuccessfully to open a document window, roll back any side-effects resulting from the attempt, and notify the user of the what happened. If OpenRecentDocument catches an exception while trying to open the file, but it is able to roll back any side effects from the attempt and notify the user, the routine will have satisfied its contract and should thus return without rethrowing the exception.
One unfortunate "gotcha" in all this is that there isn't any standard means by which routines which throw an exception can indicate whether their attempted operation has resulted in side-effects which could not be rolled back. There is no inherent way, for example, of distinguishing an InvalidOperationException which occurs unexpectedly while updating a shared data structure (which would imply that other open documents may have been corrupted), from an InvalidOperationException which occurs while updating the data associated with the document being loaded, even if one has anticipated the latter possibility and provided for it. The best one can do is either try to catch any InvalidOperationException which might occur in the latter situation near the spot that it occurs, encapsulate that exception in some other exception type, and throw that, or else have data structures maintain an "object corrupted" flag and ensure that if a data structure is found to be corrupt, all future operations on it will fail as cleanly as possible. Neither approach is at all elegant. The more common approach, which could probably be described as "hope for the best", usually works.
What are the best practices for exceptions over remote methods?
I'm sure that you need to handle all exceptions at the level of a remote method implementation, because you need to log it on the server side. But what should you do afterwards?
Should you wrap the exception in a RemoteException (java) and throw it to the client? This would mean that the client would have to import all exceptions that could be thrown. Would it be better to throw a new custom exception with fewer details? Because the client won't need to know all the details of what went wrong. What should you log on the client? I've even heard of using return codes(for efficiency maybe?) to tell the caller about what happened.
The important thing to keep in mind, is that the client must be informed of what went wrong. A generic answer of "Something failed" or no notification at all is unacceptable. And what about runtime (unchecked) exceptions?
It seems like you want to be able to differentiate if the failure was due to a system failure (e.g. a service or machine is down) or a business logic failure (e.g. the user does not exist).
I'd recommend wrapping all system exceptions from the RMI call with your own custom exception. You can still maintain the information in the exception by passing it to your custom exception as the cause (this is possible in Java, not sure about other languages). That way client only need to know how to handle the one exception in the cause of system failure. Whether this custom exception is checked or runtime is up for debate (probably depends on your project standards). I would definitely log this type of failure.
Business type failures can be represented as either a separate exception or some type of default (or null) response object. I would attempt to recover (i.e. take some alternative action) from this type of failure and log only if the recovery fails.
In past projects we'd catch all service layer (tier) exceptions at the very top of the layer, passing the application specific error codes/information to the UI via DTO's/VO's. It's a simple approach in that there's an established pattern of all error handling happening in the same place for each service instead of scattered about the service and UI layers.
Then all the UI has to do is inspect the DTO/VO for a flag (hasError?) and display the error message(s), it doesn't have to know nor care what the actual exception was.
I would always log the exception within my application (at the server side as defined in your question).
I would then throw an exception, to be caught by the client. If the caller could take corrective action to prevent the exception then I would ensure that the exception contained this information (e.g. DateTime argName must not be in the past). If the error was caused by some outage of a third party system then I might pass this information up the call stack to the caller.
If, however, the exception was essentially caused by a bug in my system then I would structure my exception handling such that a non-informative exception message (e.g. General failure) was used.
Here's what I did. Every Remote Method implementation catches all Exceptions on the server side and logs them. Then they are wrapped in a Custom Exception, which will contain a description of the problem. This description must be useful to the client, so it won't contain all the details of the caught Exception, because the client doesn't need them. They have already been logged on the server side. Now, on the client, these Exceptions can be handled how the user wishes.
Why I chose using Exceptions and not return codes is because of one very important drawback of return codes: you can't throw them to higher levels without some effort. This means you have to check for an error right after the call and handle it there. But this may not be what I want.
I've seen the following code many times:
try
{
... // some code
}
catch (Exception ex)
{
... // Do something
throw new CustomException(ex);
// or
// throw;
// or
// throw ex;
}
Can you please explain the purpose of re-throwing an exception? Is it following a pattern/best practice in exception handling? (I've read somewhere that it's called "Caller Inform" pattern?)
Rethrowing the same exception is useful if you want to, say, log the exception, but not handle it.
Throwing a new exception that wraps the caught exception is good for abstraction. e.g., your library uses a third-party library that throws an exception that the clients of your library shouldn't know about. In that case, you wrap it into an exception type more native to your library, and throw that instead.
Actually there is a difference between
throw new CustomException(ex);
and
throw;
The second will preserve the stack information.
But sometimes you want to make the Exception more "friendly" to your application domain, instead of letting the DatabaseException reach your GUI, you'll raise your custom exception which contains the original exception.
For instance:
try
{
}
catch (SqlException ex)
{
switch (ex.Number) {
case 17:
case 4060:
case 18456:
throw new InvalidDatabaseConnectionException("The database does not exists or cannot be reached using the supplied connection settings.", ex);
case 547:
throw new CouldNotDeleteException("There is a another object still using this object, therefore it cannot be deleted.", ex);
default:
throw new UnexpectedDatabaseErrorException("There was an unexpected error from the database.", ex);
}
}
Sometimes you want to hide the implementation details of a method or improve
the level of abstraction of a problem so that it’s more meaningful to the caller
of a method. To do this, you can intercept the original exception and substitute
a custom exception that’s better suited for explaining the problem.
Take for example a method that loads the requested user’s details from a text file. The method assumes that a text file exists named with the user’s ID and a suffix of “.data”. When that file doesn’t actually exist, it doesn’t make much sense to throw a FileNotFoundException because the fact that each user’s details are stored in a text file is an implementation detail internal to the method. So this method could instead wrap the original exception in a custom exception with an explanatory message.
Unlike the code you're shown, best practice is that the original exception should be kept by loading it as the InnerException property of your new exception. This means that a developer can still analyze the underlying problem if necessary.
When you're creating a custom exception, here's a useful checklist:
• Find a good name that conveys why the exception was thrown and make sure that the name ends with the word “Exception”.
• Ensure that you implement the three standard exception constructors.
• Ensure that you mark your exception with the Serializable attribute.
• Ensure that you implement the deserialization constructor.
• Add any custom exception properties that might help developers to understand and handle your exception better.
• If you add any custom properties, make sure that you implement and override GetObjectData to serialize your custom properties.
• If you add any custom properties, override the Message property so that you can add your properties to the standard exception message.
• Remember to attach the original exception using the InnerException property of your custom exception.
You typically catch and re-throw for one of two reasons, depending on where the code sits architecturally within an application.
At the core of an application you typically catch and re-throw to translate an exception into something more meaningful. For example if you're writing a data access layer and using custom error codes with SQL Server, you might translate SqlException into things like ObjectNotFoundException. This is useful because (a) it makes it easier for callers to handle specific types of exception, and (b) because it prevents implementation details of that layer such as the fact you're using SQL Server for persistence leaking into other layers, which allows you to change things in the future more easily.
At boundaries of applications it's common to catch and re-throw without translating an exception so that you can log details of it, aiding in debugging and diagnosing live issues. Ideally you want to publish error somewhere that the operations team can easily monitor (e.g. the event log) as well as somewhere that gives context around where the exception happened in the control flow for developers (typically tracing).
I can think of the following reasons:
Keeping the set of thrown exception types fixed, as part of the API, so that the callers only have to worry about the fixed set of exceptions. In Java, you are practically forced to do that, because of the checked exceptions mechanism.
Adding some context information to the exception. For example, instead of letting the bare "record not found" pass through from the DB, you might want to catch it and add "... while processing order no XXX, looking for product YYY".
Doing some cleanup - closing files, rolling back transactions, freeing some handles.
Generally the "Do Something" either involves better explaining the exception (For instance, wrapping it in another exception), or tracing information through a certain source.
Another possibility is if the exception type is not enough information to know if an exception needs to be caught, in which case catching it an examining it will provide more information.
This is not to say that method is used for purely good reasons, many times it is used when a developer thinks tracing information may be needed at some future point, in which case you get try {} catch {throw;} style, which is not helpful at all.
I think it depends on what you are trying to do with the exception.
One good reason would be to log the error first in the catch, and then throw it up to the UI to generate a friendly error message with the option to see a more "advanced/detailed" view of the error, which contains the original error.
Another approach is a "retry" approach, e.g., an error count is kept, and after a certain amount of retries that's the only time the error is sent up the stack (this is sometimes done for database access for database calls that timeout, or in accessing web services over slow networks).
There will be a bunch of other reasons to do it though.
FYI, this is a related question about each type of re-throw:
Performance Considerations for throwing Exceptions
My question focuses on "Why" we re-throw exceptions and its usage in application exception handling strategy.
Until I started using the EntLib ExceptionBlock, I was using them to log errors before throwing them. Kind of nasty when you think I could have handled them at that point, but at the time it was better to have them fail nastily in UAT (after logging them) rather than cover a flow-on bug.
The application will most probably be catching those re-thrown exceptions higher up the call stack and so re-throwing them allows that higher up handler to intercept and process them as appropriate. It is quite common for application to have a top-level exception handler that logs or reports the expections.
Another alternative is that the coder was lazy and instead of catching just the set of exceptions they want to handle they have caught everything and then re-thrown only the ones they cannot actually handle.
As Rafal mentioned, sometimes this is done to convert a checked exception to an unchecked exception, or to a checked exception that's more suitable for an API. There is an example here:
http://radio-weblogs.com/0122027/stories/2003/04/01/JavasCheckedExceptionsWereAMistake.html
If you look at exceptions as on an alternative way to get a method result, then re-throwing an exception is like wrapping your result into some other object.
And this is a common operation in a non-exceptional world. Usually this happens on a border of two application layers - when a function from layer B calls a function from layer C, it transforms C's result into B's internal form.
A -- calls --> B -- calls --> C
If it doesn't, then at the layer A which calls the layer B there will be a full set of JDK exceptions to handle. :-)
As also the accepted answer points out, layer A might not even be aware of C's exception.
Example
Layer A, servlet: retrieves an image and it's meta information
Layer B, JPEG library: collects available DCIM tags to parse a JPEG file
Layer C, a simple DB: a class reading string records from a random access file. Some bytes are broken, so it throws an exception saying "can't read UTF-8 string for record 'bibliographicCitation'".
So A won't understand the meaning of 'bibliographicCitation'. So B should translate this exception for A into TagsReadingException which wraps the original.
THE MAIN REASON of re-throwing exceptions is to leave Call Stack untouched, so you can get more complete picture of what happens and calls sequence.