Undocumented Exceptions in Enterprise Library - exception

I am using Enterprise Library's DAAB to access a database, both with ExecuteReader and ExecuteNonQuery. The problem is that these methods do not have exceptions thrown documented... How can I, then, know which exceptions should I catch?

I agree with WebTurner, I'm guessing a good place to start would be which database your connecting to, so if an ms sql database I'm guessing a couple of (perhaps many) exceptions would be:
SqlException
InvalidOperationException
http://msdn.microsoft.com/en-us/library/9kcbe65k.aspx
EDIT:
I just came across this: How can I determine which exceptions can be thrown by a given method?
Which looks liek it uses reflection to help uncover a list of exceptions that are thrown.

The problem is that there are many exceptions that will be thrown at a lower level than the enterprise library, and it would be impossible for EL to document all of these.
I suggest you use the exception handling and logging blocks to catch and log all exceptions. You can then see which ones occur and adapt the configuration of the exception handler or add new code to handle the specific execptions.

Related

Is it wrong to thow or catch the Exception Class (every Exception possible)?

I know that a question like this probably depends on what the programmer intends his program to do however at school we were taught to never throw or catch Exception (the class) and rather make sure it throws one of the subclasses more specific to the kind of Runtime error we expect can happen (eg IllegalArgumentException). However, I'm working now and in the 'real world' I see a lot of scenarios in code I work on where the previous programmers threw Exception for everything in a method or catch Exception like that rather than one of its more specific subclasses.
So I'm wondering, Is it ok to throw and catch everything like this, is it bad programming to do so?
My idea is, the way of handle the exceptions should also depend on the type of the application you are creating. For example if you are developing some kind of a framework or a library you should not try to print error messages or log them, you have throw them because it will be responsibility of the other developers who are using your framework/library to handle the exceptions gracefully when they are using your code.
If you are developing some kind of a front end application then you should be more delicate with exception handling. I think it's better you use you own exception classes when possible, because that will help you to pin point the bugs or runtime issues in your application later. When you handle exceptions you should always go from more specific exceptions to general exceptions. And finally you should handle the exceptions of the "Exception" super class so it will make sure that your application doesn't crash, preferably you should have a try-catch block in the main entry point of your application. What ever happens in handling exceptions logging the errors is a good practice when it comes diagnosing the errors later.
It is not wrong to do that but it can make your debugging life very difficult. Many people will catch the exception class and log the Exception.Message. There is not enough detail and, especially if you're working on large systems where you can't always step through the live code etc, it will be a tedious task.
I tend to catch specific exceptions and handle them accordingly BUT I also catch the Exception class to make sure all exceptions are caught going forward (An object might be changed to include more exceptions in future framework versions).
It is bad practice, just as you have learnt.
One major exception to the rule is a top-level exception handler (to catch unhandled exceptions) - the purpose of this would be to log exception so they can be read by a developer later and used to fix the application (and would normally rethrow in order to crash the application - rather than leaving it in an inconsistent state).

Why not catch general Exceptions

My VS just told me;
Warning 2 CA1031 : Microsoft.Design : Modify 'Program.Main(string[])' to catch a more specific exception than 'Exception' or rethrow the exception.
Why should I do that? If I do so, and don't catch all exceptions to handle them, my program crashes with the all-popular report-screen. I don't want my users to get such error-crap!
Why should I not catch all exceptions at once to display a nice warning to the user saying: "Something went wrong, don't care about it, I will handle it, just be patient"?
Edit: Just saw I have a dupe here, sorry for that Dupe
Edit2: To clarify things; I do exit the program after any exception has been catched! I just don't want my user to see that "report to microsoft" dialog that show up when an unhandled exception is raised in a console-application!
Swallowing exceptions is a dangerous practice because:
It can cause the user to think something succeeded when it actually failed.
It can put your application into states that you didn't plan for.
It complicates debugging, since it's much harder to find out where the failure happened when you're dealing with bizarre/broken behavior instead of a stack trace.
As you can probably imagine, some of these outcomes can be extremely catastrophic, so doing this right is an important habbit.
Best Practice
First off, code defensively so that exceptions don't occur any more than necessary. They're computationally expensive.
Handle the expected exceptions at a granular level (for example: FileNotFoundException) when possible.
For unexpected exceptions, you can do one of two things:
Let them bubble up normally and cause a crash
Catch them and fail gracefully
Fail Gracefully?
Let's say you're working in ASP.Net and you don't want to show the yellow screen of death to your users, but you also don't want problems to be hidden from the dev team.
In our applications, we usually catch unhandled exceptions in global.asax and then do logging and send out notification emails. We also show a more friendly error page, which can be configured in web.config using the customErrors tag.
That's our last line of defense, and if we end up getting an email we jump on it right away.
That type of pattern is not the same as just swallowing exceptions, where you have an empty Catch block that only exists to "pretend" that the exception did not occur.
Other Notes
In VS2010, there's something called intellitrace coming that will allow you to actually email the application state back home and step through code, examine variable values at the time of the exception, and so on. That's going to be extremely useful.
Because programs that swallow (catch) exceptions indiscriminately, (and then continue), cannot be relied upon to do what it is they are expected to do. This is because you have no idea what kind of exception was "ignored". What if there was an overflow or memory access error that causes the wrong amount to be debited from a financial account? What if it steers the ship into the iceberg instead of away from it ? Unexpected failures should always cause the application to terminate. That forces the development process to identify and correct the exceptions it finds, (crashes during demos are a wonderful motivator), and, in production, allows appropriately designed backup systems to react when the software experiences an "unexpected" inability to do what it was designed to do.
EDIT: To clarify distinctions between UI components, and service or middleware componentrs.
In Service or Middleware components, where there is no user interacting with the code component from within the same process space that the code is running in, the component needs to "pass On" the exception to whatever client component imnitiated the call it is currently processing. No matter the exception, it should make every possible attempt to do this. It is still the case, however, tjhat in cases where an unexpected, or unanticipated exception occurs, the component should finally terminate the process it is running in. For anticipated or expected exceptions, a velopment analysis should be done to determine whether or not, for that specific exception, the component and it's host process can continue to operate (handling future requests), or whether it should be terminated.
You should handle the exact exceptions you are capable of handling and let all others bubble up. If it displays a message to the user that means you don't quite know what you can handle.
Having worked on equipment used by emergency responders, I would rather the user see an ugly error message than to accidently swallow an exception that misleads the user into believing everything is "ok". Depending on your application, the consequence could be anything from nothing to a lost sale to a catastrophic loss of life.
If a person were going to catch all exception, show a better error dialog, and then quit the application, that's ok.. but if they are going to continue running after swallowing an unknown exception, I would fire a person for that. It's not ok. Ever.
Good coding is about practices that assume humans make mistakes. Assuming all "critical" exceptions have been caught and handled is a bad idea.
Simple answer: you are supposed to fix your bug. Find the place that throws the exception and unless it is beyond your control - fix it.
Also catching (without rethrowing) all kinds of exception violates exception neutrality. In general you do not want to do this (although catching exceptions in main does look like special case)
Since your warning message shows that this is in Main(), I'll assume that in lower levels, you do catch only more specific Exceptions.
For Main(), I'd consider two cases:
Your own (debugging) build, where you want all the exception information you can get: Do not catch any Exceptions here, so the debugger breaks and you have your call stack,
Your public releases, where you want the application to behave normally: Catch Exception and display a nice message. This is always better (for the average user) than the 'send report' window.
To do this nicely, just check if DEBUG is defined (and define it, if VS doesn't do this automatically):
#if DEBUG
yadda(); // Check only specific Exception types here
#else
try
{
yadda();
}
catch (Exception e)
{
ShowMessage(e); // Show friendly message to user
}
#endif
I'd disable the warning about catching general Exceptions, but only for your Main() function, catching Exception in any other method is unwise, as other posters have said already.
There is a way to suppress certain messages from code analysis. I've used this for this exact reason (catching the general exception for logging purposes) and it's been pretty handy. When you add this attribute, it shows you've at least acknowledged that you are breaking the rule for a specific reason. You also still get your warning for catch blocks that are incorrect (catching the general exception for purposes other than logging).
MSDN SuppressMessageAttribute
I am all for catching specific known exceptions and handling state...but I use general catch exceptions to quickly localize problems and pass errors up to calling methods which handle state just fine. During development as those are caught, they have a place right next to the general exception and are handled once in release.
I believe one should attempt to remove these once the code goes into production, but to constantly be nagged during the initial code creation is a bit much.
Hence turn off (uncheck) the warning by the project settings as found in Microsoft.CodeQuality.Analyzers. That is found in the project settings under Code Analysis:
All answers are good here. But I would mention one more option.
The intention of author to show some fancy message is understandable.
Also, default Windows error message is really ugly. Besides, if application is not submitted to "Windows Excellence Program" the developer will not receive information about this problem. So what is the point to use default runtime handler if it does not help?
The thing here is that default exception handler of CLR host ( https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2008/9x0wh2z3(v=vs.90)?redirectedfrom=MSDN ) works in a very safe way. The purpose of it is clear: log the error, send it to developer, set the return code of your process and kill it. The general way of how to change that is to write your own host. In this case you can provide your own way of handling exceptions.
Still, there is an easy solution which satisfies CA1031 and still most of your needs.
When catching the exception, you can handle it your own way (log, show the message etc) and at the end you can set the process result code and do the exit (using the mix of Thread.Abort and "Exit" methods, for example). Still, at the end of your catch block you can just put "throw;" (which will never be called because of ThreadAbortedException, but will satisfy the rule). Still there are some cases, like StackOverflowException, which can't be handled like that and you will see that default message box, for fixing which you need to fallback to custom CLR host option.
Additionally, just for your information, you application can run several threads (besides that one which execute Main method). To receive exceptions from all of them you can use AppDomain.UnhandledException. This event does not allow you to "mark" the exception as handled, still you can freeze the thread using Thread.Join() and then do the job (log, msgbox, exit) using another (one more) thread.
I understand all this looks a little tricky and may be not right, but we have to deal with the implementation of AppDomain.UnhandledException, ThreadAbortException, CorruptedState exceptions and default CLR host. All of this eventually does not leave us much of choice.
When you catch general exceptions, you get the side effect of potentially hiding run-time problems from the user which, in turn, can complicate debugging. Also, by catching general exception, you're ignoring a problem (which you're probably throwing elsewhere).
You can set up your try catch to catch multiple different behavior types and handle the exception based on the type. For most methods and properties in the framework, you can also see what exceptions they are capable of throwing. So unless you are catching an exception from an extremely small block of code, you should probably catch specific exceptions.
In VS you can setup a custom error page to show your users when something goes wrong instead of catching it in a try-catch. I'm assuming since you're using VS that you're using ASP .NET. If so add this tag to your Web.Config under the System.Web tag:
<customErrors mode="RemoteOnly" defaultRedirect="~/CustomErrorPage.aspx" redirectMode="ResponseRewrite" />
You can also catch all uncaught exceptions in the Global.asax file (if you don't have it already: Right-click on web project, select Add Item, and search for it). There are a bunch of application wide event handlers in that file like "Application_Error" that catches every exception that isn't caught within your application so you don't have to use Try-Catch all the time. This is good to use to send yourself an email if an exception occurs and possibly redirect them to your homepage or something if you don't want to use the customErrors tag above.
But ultimately you don't want to wrap your entire application in a try-catch nor do you want to catch a general Exception. Try-catches generally slow down your application and a lot of times if you catch every general exception than it could be possible that you wouldn't know a bug exists until months or years later because the try-catch caused you to overlook it.

The right time to handle all exceptions

I've done a few projects so far, and i've noticed that every single one i've written entirely without any exception handling, then at the end I do a lot of tests and handle them all.
is it right? i get thousands of exceptions while testing (which I fix right away) that if i've handled it i wouldn't see exactly where it is(when not using breakpoints or displaying it anywhere.. but it doesn't seem as practical) So I fix issues by checking any exceptions, then in the end I handle them anyway for any possible one that might have escaped (of course).
What about you? when do you guys take care of exceptions ?
Personally, I always define a global unhandled exception manager appropriate to the application type and have that log and email exceptions to my dev team. During QA, we'll then start to add specific exception management to routines that have predictable (and recoverable) issues. In every case possible, we add defensive programming code so that exceptions don't happen at all. (There's no need to trap an exception if you can test before you try code that could fail.)
My apps tend to end up with lots of defensive code (which should be built in from the start) and only some specific exception handling.
I prefer test-driven development. If there is an expected error condition, then test for it. If an unexpected error crops up, make a test for it, then fix it.
I would say that this is backwards (but common).
You might want to look into test driven development, and test first design
Hint: think of a behavior, write code to test for it, add it to your application.
I would definitely consider the exceptions thrown as you develop each interface and module.
That way you can test that they're reliably thrown (when you expect and not when you don't). Components consuming these components can then be written to be aware of these exceptions and handle (or not as they require).
It seems to me that you're ignoring some functionality of the components you're developing. I'll virtually always test for both correct functionality and the exceptional circumstances, to cover as many scenarios as I can as early as I can.
The answer to this one is a very clear "it depends".
You need to look at the specific situation; is an exception being thrown in a specific piece of code where it's possible to recover or handle the "exceptional" situation resulting in the exception being thrown? In that case, yes, catch the exception and deal with it at that level.
On the other hand, are you talking about non-recoverable errors? Then sure, catch them at a more global level, or possibly not at all (ie if there's nothing you can do about the exception, why are you catching it?)
The rule for where to catch exceptions usually is: wherever is the place you can meaningfully handle them.
Sometimes it depends upon the technology or target platform. I usually prefer an exception handling layer that takes care of all the exceptions. Each and every block of code is inside a try catch block.
Bottom line is that no exception should get caught by the OS or any other entity outside the program or code.
The beauty of exceptions compared to say returning error codes from API's is that you don't have to check for exceptions at every layer in your code. You can catch specific exceptions to determine specific error conditions and perhaps handle the error or rethrow a more appropriate exception. You also have to catch exceptions at a high level in your application to avoid unhandled exceptions.
One thing to note is that generally the user of the exception is the developer and not the end-user. The later normally doesn't appreciate the technical details of exceptions.
The most common thing I've seen is developers making a conscious choice as to what level to handle exceptions, and allow them to be thrown. Typically it will be at the level of a worker thread, or a high level of business logic. Allow the exceptions to happen, and have a blanket method of handling / logging them and protecting the user from them.
Timing is the only difference between what typically happens and what you do. Plan for it in your applications from the beginning, and do exception handling at high levels.
Fixing specific exceptions is done via your method of fix it when it's a problem. Sometimes a library I use will needlessly use exceptions to communicate information, and I will add specialized exception handling around all calls to that library. Often I will do this in a wrapper class that hides the implementation and exception handling from the rest of my application.

Exceptions and Abstractions

When should you throw a custom exception?
e.g. I have some code that connects to a server. The code that connects to the server throws an IOException when it fails to connect. In the context of the method it's called, this is fine. It's also fine in the network code.
But as this represents not having a connection (and therefore not working) the exception goes all the way up to the ui. At this stage, an IOException is very ambigous. Something like NoConnectionException would be better.
So, my question is:
At what stage should you catch an exception to instead throw another (custom) exception that better fits the abstraction?
I would expect exceptions to talk in terms of what I've asked the originating method to do. e.g.
read -> ReadException
connect -> ConnectException
buildPortfolio -> FailedToBuildPortfolioException
etc. This abstracts away what's going on under the covers (i.e. are you connecting via sockets etc.). As a general rule, when I create an interface for a component, I often create a corresponding exception or set of exceptions. My interface will be called Component, and my exceptions are usually ComponentException (e.g. RateSource and RateSourceException). It's consistent and easy to export to different projects as a complete component set.
The downside is that you create quite a lot of exceptions, and you may have to perform quite a lot of translations. The upside is that (as you've identified) you get little to no abstraction leakage.
At some point during the hierarchy of method calls (and thus exceptions) you may decide that no recovery can take place (or it's at an inappropriate place) and translate to unchecked exceptions to be handled later.
I know this is tagged as "language-agnostic", but I don't think it really is. Coming from a C++ perspective, I expect very few basic operations to throw an exception - the C++ Standard Library only uses exceptions in a very few places. So my own code is often the first place where exceptions can be generated. In that code, I like a very flat hierarchy - I don't want to be messing with hundreds of catch() clauses later in the code, and have never understood Java and C#'s apparent obsession with creating Baroque heirarchies of class and namespace.
So, for my C++ code - one type of exception, containing a meaningful error message, per library. And one for the final executable.
I think there are two questions hidden here:
a) When should one hide an exception behind a different exception.
b) When should one use a custom exception for this.
a) I'd say: when ever an exception travels across the border of two layers in the application, it should get hidden behind an exception that is more apropriate for the new layer.
Example: because you are doing some remote stuff, you get a ConnectionWhatEverException.
But the caller shouldn't be aware of Connection problems. Since he just wants to get some service performed, so he gets a ServiceOutOfOrderException. The reason for this is: Inside the layer, doing remoting, you might to do something usefull with a ConnectionException (retry, write into a backout queue ..). Once you left that layer, nobody knows how to handle a ConnectionException. But they should be able to decide, what do do, when the Service does not work.
b) When there is no matching existing Exception. There are a couple of useful Exception in Java for example. I use IllegalState and IllegalArgument quite often. A strong argument for a new exception class is, if you have some useful context to provide. For example the name of the service that failed could be an argument of a ServiceFailedException. Just don't create a class for every method call, or anything to that effect. 100 Exception classes aren't a problem, as long as they have different behavior (i.e. at least different fields). If they differ only by name and reside on the same abstraction level, make them one Exception, and put the different names in the message or a single field of that exception class.
c) At least in java there is the discussion about checked exceptions. I wrap those directly in an unchecked one, because I hate the checked kind. But that is more an opinion then advice.
Is there any case where you would get NoConnectionException which isn't caused by an IO issue? Conversely, is knowing whether the cause is IO based or not going to help the client recover sensibly?
When should you throw a custom exception?
I. When you can provide more (diagnostic) information.
Note: this additional information may not be available at the place where the original exception (IOException) was thrown. Progressive layers of abstractions may have more information to add like what were you trying to do which led to this exception?
II. When you must not expose implementation details: i.e. you want the (illusion of?) abstraction to continue.
This may be important when the underlying implementation mechanism can change. Wrapping the underlying exception in a custom exception is a good way of insulating your clients from implementation details (by lifting the level of abstraction)
III. Both I and II
NOTE: Furthermore your clients should be able to tune into the exact level of information they are interested in or rather they should be able to tune out anything they are not interested in. So it's a good idea to derive your custom exceptions from IOException.

Exceptions over remote methods

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.