I noticed there is a IOException type in Control.Exception as well, what's the point of having a separate System.IO.Error module and IOError type? Is it there just because of historical reasons? Should I avoid using it and prefer Control.Exception.IOException?
Yes, it is just for historical reasons.
System.IO.Error has an IOError type which is just a type synonym for IOException (in GHC anyways).
GHCs fancy exception hierarchy mechanism is not part of the Haskell standard. So, IOError is used for compatability with Haskell 2010.
If you are happy with being GHC specific, IOException and the entire Exception hierarchy is simply better and should be preferred.
IOError is the old Haskell98 IO exception type. Control.Exception and other newer variants are not necessarily Haskell98-compatible, but we can embed the old Haskell98 errors in them, hence the type synonym.
Related
In programming, are exceptions always errors (divide by zero, access violation, ...)?
If not, can you provide examples of exceptions which are not errors?
Thanks.
Exceptions are often used to manage errors, they make error handling easier but they aren't always errors.
Every unordinary situation that require a separate code path could be a candidate for an exception.
Although the use of exceptions for control flow can be confusing (it depends largely on the language), they can be used to break out of a loop.
Sometimes you can use an exception to check if a string contains a value or if a file exists.
You can use exceptions to terminate threads collaboratively.
You should also consider that different languages have different conventions about when exceptions should be thrown (e.g. Python > C++ > Objective C).
Objective C is an extreme:
When you’re writing code with Objective-C, exceptions are used solely for programmer errors
(iOS Developer Library - Dealing with Errors)
but this isn't the norm.
An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions.
check here
The handlers I implemented override SimpleChannelHandler messageReceived, channelConnected and exceptionCaught methods.
Throwing a base Exception type means PMD complains "Signature Declare Throws Exception".
What is the best way to handle Netty exceptions so as not the throw base Exception types?
My guess is to remove the "throws Exception" from all my handlers. Then any exception that occurs will eventually get propagated up to the exceptionCaught() method in the last upstream/downstream Handler in the pipeline. Is this a correct assumption?
Although I happen to agree with PMD on this, the object model of Netty is different and uses a raw Exception. If you are programming against the Netty API, it would probably be better (for consistency, readability, etc.) to follow their model.
Don't let a static analysis tool be the deciding factor on your code. Sometimes there are exceptions (nice pun, not intended)
It dawned on me that I've never seen a single exception hierarchy for which creating subclasses but catching the parent class was actually useful (except, of course, for the base Exception class, that has to be derived).
Are exception hierarchies really useful, xor should all exceptions be derived from language's base exception class?
Exception hierarchies are useful for grouping related exceptions together, when you need different granularity of catching in different places.
Putting all application exceptions in one place is the commonest use case. This allows you to catch MyAppException any time that you want to trap all errors coming from your application, but still catch more specific exceptions when appropriate. (In .NET, the ApplicationException class was meant for this, but it's been deprecated for various reasons.)
But you can also group exceptions together at module boundaries, or in any other way that makes sense. Use FooModuleException for exceptions coming from the Foo module, but catch and handle FooModuleMustFrobnicate specially internal to Foo. Or any equivalent situation.
I've used all of these patterns at different times.
TL;DR
Exception hierarchies are useless for catching exceptions (except for base differentiation btw. non-recoverable system errors (Java Error) and "normal" runtime exceptions. The notion that "you need different granularity of catching in different places" is IMHO fundamentally flawed. (Except, to reiterate, to differentiate between exceptions and assertions and other system wide unrecoverable stuff.)
Small exception hierarchies make sense in todays languages as a means of constructing different errors with as rich information as possible.
I am slowly coming to consider the whole concept of arbitrarily typed exceptions, as I see them implemented and supposed-to-be-used in C++, C# and Java as totally useless.
The problem is not so much the exception hierarchy per se, but that when I write code, and exception are exceptional, I don't care what type of exception was thrown for the purpose of catching it.
In all my coding in C++, Java and C#, I found -- for the exceptional exceptions, that were not misused for control flow -- not one case where I wanted to filter (i.e. catch or not catch) the exceptions by their "hierarchical" type. That is, there are rare cases where a function throws 3 different exceptions, and I want to specifically handle one of them, and handle the two others as general "fail" (like described below) but I never ever encountered this in a case where the exception hierarchy was useful in that I could meaningfully group the two cases by base classes.
If any operation (where I care) in my program fails with any exception, then this operations is considered failed, and:
I get what info I can from the caught object
continue with contextualized error handling (re-throw, display error, log, re-try, recover, etc.)
I think Java is the only of the three languages that at least has the right approach with their hierarchy, namely:
Throwable not used in user code
Error the stuff you never want to catch - just core dump
Exception - for all the stuff you basically always want to catch (except for when an Interface is botched and uses an Exception when it really shouldn't)
//
The hierarchy of C++'s <stdexcept> has the right basic approach in differentiating between logic_error - basically assertions - and runtime_error - stuff that just unexpectedly failed. (The subclasses of theses are largely irrelevant when catching.)
Except of course that too much stuff derives directly from std::exception so you can't make use of the differentiation provided by runtime and logic error. (And of course any code is free to throw whatever they want, so chances are good that there's a bunch of logic_error derived classes that really should be runtime_errors and vice-versa.
To quote another answer:
Exception hierarchies are useful for grouping related exceptions
together, when you need different granularity of catching in different
places.
but in my experience I never want "catching in different places", because it just doesn't make sense.
I either want catching, in which case I catch everything (modulo stuff like the Error class exceptions from Java) or I don't want to catch, in which case the hierarchy is not needed, because there is no catch.
Take opening and reading from a file:
If there is (would be) any exception type I specifically care about, because I can do something about it ("recover"), then this should not be reported as an exception at all, because it is normal control flow. (If the error is such-and-such, I can do such-and-such basically locally.)
If on the other hand, I can't do anything about an error but record the file operation as failed, then having any catch granularity is utterly useless.
I've never created a single exception hierarchy for whole application, because an exception in general can bring different semantic and, therefore, needs to handled differently.
Some exceptions inform about system faults, another exceptions inform about bugs, and some other - about some exceptional condition, that could be gracefully recovered on higher level.
For this "business-logic" exceptions exception hierarchy can help you not to violate open-closed principle during overriding some methods in descendants.
Consider following example:
public abstract class Base
{
/// Perform some business-logic operation
/// and throw BaseFooException in certain circumstances
public abstract void Foo();
}
public class Derived1 : Base
{
/// Perform some business-logic operation
/// and throw DerivedFooException in certain circumstances.
/// But caller could catch only BaseFooException
public abstract void Foo() {}
}
class BaseFooException : Exception {}
class DerivedFooException : BaseFooException {}
Exception hierarchy may be helpful in custom framework or in specific libraries, but in general case (in business applications) I don't think that creating one deep and wide exception hierarchy is a good idea.
Why is it a "bad idea" to throw your own exceptions?
found here
In general, it is perfectly fine to throw your own exceptions. Perhaps what you meant to ask was "When is it not necessarily a good idea to throw my own exception?"
One case is when you should be throwing a standard exception. For example, if your method takes a file name and is supposed to return a file, you should probably throw your platform's standard FileNotFoundException rather than throw PeanutPowersFileNotFoundException. If you really want to throw your own exception, you should probably have it extend the standard FileNotFoundException.
Update: Bloch explains this in Item 60 of Effective Java
It's not. You should create and throw custom exceptions whenever you have an exceptional situation.
It isn't provided they are derived from whatever the standard base exception type is (std::exception in c++, or Exception in python, etc...)
If they _aren't_derived from the normal base type, then other people may not catch them when they are expecting to catch all exceptions - which would be a bad thing.
It's not wrong to create your own exception type. However, before going through creating your own, you should check whether your framework already provides an exception that fits.
From the .Net design guidelines:
Consider throwing existing exceptions
residing in the System namespaces
instead of creating custom exception
types.
Do create and throw custom exceptions
if you have an error condition that
can be programmatically handled in a
different way than any other existing
exceptions. Otherwise, throw one of
the existing exceptions.
Do not create and throw new exceptions
just to have your team's exception.
I believe you might be asking why is it a bad idea to re-throw exceptions.
By "rethrow", I mean catching an exception and than generating a new one and throwing it. This can be problematic, as you could end up consuming the original stack trace and loosing all context of the error.
You should not invent your own type of Exception, unless you have something extra you want to add to the Exception type.
If you want to tell the user of your API that they have provided an invalid argument, you should throw an ArgumentException, but if your library fails because of some library specific reason, that you can't convey in a regular exception, you should roll your own and let it contain the info the developer needs.
To continue Peter's response another case when throwing an exception is not a good idea is if you use throwing exceptions to control the business logic of your program.
As long as the exception you are throwing is derived from a proper object, and conveys just that - exceptional situation, throwing an exception is totally acceptable.
Using throwing exceptions to control business logic in addition to being a bad design pattern has also performance implications - throwing and catching exceptions is rather expensive as compared to branching based on the results returned from the method
There's nothing wrong with creating your own exceptions, which can be tailored to convey exactly the information which is appropriate for your situation. A ConfigFileNotFoundException conveys more information than a FileNotFoundException (which file didn't we find?).
But, by all means, make sure that you catch and handle each and every custom exception inside of your code. When the exception flies to some place outside your module (call it package, call it namespace), those folks out there will not even know that it exists, much less what to do with it. Except for a catch (Throwable t) {/* whut? */}.
To me it seems that the question is to catch inexperienced candidates trying to fake experience. There's nothing wrong about throwing your own exceptions in my opinion, and as you can see to everyone else that answered here.
It's not a bad idea at all. If an exceptional situation arises, an exception should be thrown to handle it, especially if you're designing code that others may use, may receive bad input, etc.
It is a bad idea to use exceptions where they're not absolutely necessary, such as situations that are recoverable by normal checks in code or as part of normal execution, since they do have a lot of overhead associated with them. I imagine that's where you may have gotten the idea that they're a bad idea in general. But for what they're meant to do (flagging an exceptional situation that your code isn't equipped to handle), they're absolutely the best tool.
And if you do create custom exceptions for code others might use, do document what they are and what they mean. That way later users of your code will know that they're possible and what they mean if they arise, and can handle them appropriately.
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.