Java: Throwing exceptions - java

Is it a good idea to pass an object to a constructor when throwing an exception?
Let's imagine that there is next code somewhere in service package.
throw new MyException(object);
MyException class:
Object object;
public MyException(Object object) {
super();
this.object = object;
}
public Object getObject() {
return object;
}
And later, let's say, in GUI we have to handle the exception thrown in service. We just catch an exception and want to access object passed in the constructor. This works. But is it a correct from the point of style?
Is the use of getObject() a correct approach?

I would say it depends on what you are doing with getObject. If you are just using it to report the error or manage the recovery from the exception then there's nothing wrong with this. I would pass something more specific than an object. For example, I might give the exception information about the cause of the error and capture any useful information that might help solve the error.
If, on the other hand, you are using this object to continue some normal branch of control flow, then that wouldn't be considered a normal use of exceptions! To repeat the obvious, exceptions are for exceptional situations and nothing more. If you're doing something else with them it's generally bad idea.
If you are using an exception to capture results that you are processing later then that's a bad design smell. Look at refactoring your code to write those objects out to a store for processing later, or some such. Don't abuse exceptions.

In general, yes, it's good to add data to exception objects which might be useful to the code handling the exception.
However, a getObject() method that returns an Object is way too generic - the name of the method and preferably also the type of the object should be specific to the exception - create multiple exception classes if necessary, then you can distinguish them in catch blocks.
Finally, this kind of thing could be abused for regular control flow. I do not agree with the standard dogma that this is inherently "evil" - exceptions are a control flow mechanism. But they're one that's bad for maintainability because it connects pieces of code implicitly. So it should only be used if you really need a way to pass control flow several levels up the call stack and have thought hard about alternatives.

As always, it will depend on your system strtucture and on what you want to achieve, but IMO this is an acceptable way to go.
Indeed, this is the way the default exception API handles the error messages and causes, passing them as constructor parameters (see Exception constructors API Doc) to be handled later.

The class that catches the exception depends on the (static) class of the object that is encapsulated in the exception. It's usually a good idea to minimize dependencies. That's why I would not encapsulate classes, that are internal to a component, into exceptions. I would encapsulate public classes of a component in an exception only if the exception and the encapsulated class belong to the same component.

Related

How to avoid creating custom exception classes whilst still throwing exceptions at an appropriate level of abstraction?

I'm reviewing my understanding of exception handling (in the context of Java), and trying to figure out what types of exceptions are most appropriate to throw. One comment that I'm regularly seeing is that it is generally better to avoid creating many custom exceptions - it is better to use the "widely understood" standard exceptions, and only "create a custom exception type when you need to annotate the exception with additional information to aid in the programmatic handling of the symptom."
However, this seems somewhat in contrast to the idea that you should "throw exceptions at the right level of abstraction". Looking at an example from Uncle Bob's 'Clean Code' the following examples are provided for an Employee class:
Bad: public TaxId getTaxId() throws EOFException
Good: public TaxId getTaxId() throws EmployeeDataNotAvailable
So, how do I consolidate these two "recomendations" - that you should only throw exceptions at the right level of abstraction, and you should rarely create custom exception classes. In addition, when searching for information on the standard exceptions in Java, there is very very little well presented and formatted information on what standard exception classes are available - I'm looking for standard exceptions that would semantically still seem to be appropriate for calling classes, but not finding much to go on. Of course you can find the what exception classes are available in the jdk documentation, but just the general lack of info and discussion online seems strange.
So, this is where I'm at right now. Any suggestions and comments are much appreciated!
The level of abstraction is judged to be right or wrong by the user of your code. To justify an existence of AExeption and BException there should be a use-case where the user differentiates between them, e.g:
} catch(AExeption ae) {
// do something
} catch(BException be) {
// do something different
}
as opposed to always:
} catch(AExeption ae | BException be ) {
// do something
}
My experience is that real world systems tend to go easy on the amount of logic that goes into the programmatic handling of the symptom
I don't think there's an specific answer for your question. In my projects, I tend to follow these guidelines for custom exception classes:
If I can encounter with an exception in a method, check if the exception can be described by any of the subclasses of Exception or, if possible, a subclass of RuntimeException. The javadocs provide enough info about the basic classes that extend from both Exception and RuntimeException and each exception class could also have more subclasses that weren't listed before e.g. IOException.
If there's no subclass of Exception or RuntimeException or any, create a custom exception class or reuse one previously created but with a distinct message. Usually, I tend to create these classes extending from RuntimeException to avoid clients of the method using try-catch blocks. If there's the need to handle the exception in the client of this method, then it should extend from Exception.
The custom exception classes are associated to a process or specific event in the application.
If developing a business application, then the name of the exception can be related to the business process you're working with. For example, if I'm developing a process that creates a bill from a set of input data (e.g. products, services, customer data, etc), then I would provide at least 2 custom exception classes:
ElementNotFoundException, probably for not finding a specific kind of input e.g. missing product or Customer#billingAddressLocation is null due to a wrong migration of the data of some customer.
BillGenerationException, generated when there's a problem after collecting the necessary data to generate the bill and in the exact process of generate the bill.
It's quite philosophical question.
But in general it means that you should create your own exception with considering of existing ones.
Example :
In case of usage some external service and this service is unavailable
, in this case I wouldn't recommend you to throw your own exception,
because "Connection Refused" or "Connection timed out" will understand
on the spot every programmer after you, for checking your custom
exception programmer will need to go to source code and spend some
time to understand your exception after noticing it in production
logs.
But if I see that my wrapper will be clearer for such case I am adding my wrapper.
There is no contradiction between using exceptions of the right level of abstraction and refraining from creating new exception classes. What you must do is choose the most appropriate existing exception class for the particular method you are interested in if you can.
So if the clear meaning of a getTaxiId method does not suggest the method performs I/O, declaring it to throw an IOException of any kind would be inappropriate. You would then have to search the other existing exception classes for a more approriate exception class. If you did not find such a class, you know it is appropriate to create a new exception class.
I think Uncle Bob is looking at the problem from the wrong end.
You throw an exception to unravel the call chain and inform a non-local piece of logic that something unexpected and detrimental happened and allow it to respond.
I can understand wrapping an EOFException and all sorts of bad data problems into some generic InvalidDataException but providing a specific EmployeeDataException seems like overkill.
It may be useful for the calling process to (say) know that there was a local data exception and not, for example, a lost connection. That way it could abandon a unit of work but realistically continue trying to process the next one.
So, do throw at an appropriate level of abstraction - for the catcher to respond usefully.
If you think about it, if you create a different exception for each object type, someone will have to maintain catchers for all object types in play!
Tomorrow a new exception called AddressDataException is introduced and various (obscure) catcher chains need that added as yet-another-data-exception category.
Of course the answer is to introduce a DataException category as super-class to all those specialised ones.
But as soon as you do that you'll change all the handlers to catch the generic exception and realise that the correct level of abstraction is a generic DataException because that's what is useful to the catcher.

Should exceptions without messages be thrown?

Should exceptions without messages ever be thrown? In what cases? For example, when subclassing Exception, should a constructor with no parameters even be given?
public class LexerException extends Exception {
public LexerException(String message) {
super(message);
}
}
or
public class LexerException extends Exception {
public LexerException() {
super();
}
public LexerException(String message) {
super(message);
}
}
Should exceptions without messages ever be thrown? In what cases?
An exception without a message will be thrown any time some code instantiates and throws an exception without a message. Anyone can write code like that.
Of course, if the exception that you are trying to throw does not allow you to instantiate it without a message ... or a with null message ... then you can't. But I've never come across an exception class that insists that the exception is non-null.
One case where exceptions typically have no message is NullPointerException when it is thrown by the JVM itself.
If you are asking should it ... in the sense of whether it is good practice to write code that throws exceptions without a message, the answer is (IMO) No. But you can make up your own mind. (I guess, if the exception name says all that there is to be said, then a message would be redundant. However, it is always useful to have extra information in the stacktrace when debugging.)
Re these comments:
Generally, you should avoid custom exceptions. Use ones that already exist. – mre
Why should I avoid custom exceptions? – Kyranstar
The point is that before you code a custom exception, you should look to see if there is an existing exception that means the same thing as your proposed new one. For example, don't write a custom IllegalLexerArgumentException exception when there is an existing IllegalArgumentException that would serve your purposes.
Why?
For the same reasons that we don't write (say) custom collection classes without good reason. It is a bad idea to write unnecessary code, 'cos that is just more code to compile and test, more space at runtime, more code for the maintainer to read, etc.
Because having lots of exception classes that mean the same thing can make exception handling messy. This effect gets worse as you combine / reuse more libraries to make large applications.
If you don't give the exception any message so you can pop-up the message into anther position when you get the error, but it's recommended to give every exception you create a message and to create an instance of this exception and to throw it.
If the documentation explicitly states there is a single case triggering the exception, then IMHO it is not require to have a message in the exception. Otherwise, it is. A good rule of thumb is: Make it easy for whoever is going to use/debug that code.
Well, honestly I've just searched our code and we use Exceptions without messages, but they are really obvious ones. Like:
UsernameCantBeEmptyException// example only
I think this depends on the use case. The NullPointerException for instance has no message. What could be helpful? No idea. On the other hand there where versions of java where the ClassCastException had no message. That's extremly annoing as the type that should be casted is hart to figure out and is available to the program.
As long as I've no idea for a use case where skipping the message seems appropiate, I'd provide no empty constructor. AFAIK a lexer figures out things like this variable has that type and thus that acion is appropriate or not. This would indicate that the exception message might even have to be presented to he end user. In such a case even localization might be mandatory. If so even some 'factory infrastructre' might be a good idea.
On custom exceptions in general: There's been a tendency to do that to often and then many figured out that in fact no custom exceptions have ever been needed. And in fact there are even hudge programs that need not a single one. On business I work on a 200kLOC program and I don't think we have one. But for sub-systems with specific needs on handling (Like catching all the LexerException to show them in a specific way, separate them from programming bugs in your own code, whatsoever) it might make much sense to have a few. I'm working on a small OSS project and there I have even more than one. But you should always keep in mind that additional exception type must make the exception handling simpler not more complicated. If you often have several catch block one after another, then your definitly on the wrong track. That's a typical symptom of unnecessary custom exceptions.

Is there an advantage to wrapping exceptions with Custom exception types in Java

I have a class XYZ whose public functions throw Exceptions.
I have been advised that all public functions exposed by XYZ should throw exceptions called XYZDataException or XYZSystemException. So even if I get other exceptions within the public methods they need to be wrapped by these XYZExceptions.
I have a couple of questions:
What is the advantage of wrapping exceptions with XYZException?
What is the advantage of differentiating between System and Data exceptions?
To me it feels right to just throw whatever exception occurs without wrapping it further.
A lot of Exception handling depends on how you plan on extending it later on. For example, if developer B came along and wanted to modify some of your code, it would be a lot easier if he understand what Exception meant what in which case. In that case, having specific Exceptions makes more sense.
As to breaking up System and Data exceptions - a Data exception would basically be something that should be non-fatal that occurs because of bad data. A System exception would be because your System failed in some way. Again, this all points to how you want to use it later on. If you want to use your code solely, and you don't care about how your exceptions come back out, then by all means, go with what is easiest at the time.
I have found that when working with other developers on a project, it is a lot easier for them to grasp what is going on when you subclass your Exceptions and throw them in specific cases.
Hope this helps!
Yes, it means they can be explicitly caught by code that knows how to handle them.
for instance, imagine you had:
class MyRecoverableException extends Exception {
...
}
You could then have code that can differentiate between them automatically, and react accordingly, such as:
try{
// ... do something ...
}catch(MyRecoverableException e) {
// Recover
}catch(Throwable t) {
// Log fatal reason, and exit gracefully.
}
Obviously how many you need is a problem to be solved by you, the application developer, but a clean separation can make all the difference when working out what went wrong, and subclassed exceptions can hold additional properties, used to pass pertinent information to handlers about the exceptional circumstances that brought them about.
Having a base type to extend from for your application/library never hurts either - if for no other reason than to allow separation of source when logging - but the exact hierarchy and complexity required beyond that depends entirely on the project. Some designs have natural and obvious choices, some require a bit more forethought (and occasionally a bit of afterthought and refactoring).
As usual, "it depends". As a general rule it does not make sense to blindly create an exception hierarchy on a per-class basis. App-specific exceptions should group exceptions in a way meaningful to that particular app, so there might be a top-level exception, then sub-classed exceptions for things like the data layer, communication layer, utilities, whatever.
The advantage is that higher levels dealing with those exceptions are not exposed to the implementation details that generate those exceptions. Also, perhaps to a lessor degree, exceptions may be grouped more meaningfully (is it relevant that it was an IOException, or is it enough to know there was a problem writing to whatever output store you're using).
Another great advantage is that app-specific information may be captured in the custom exceptions. Things like user IDs, account numbers, etc.--any application state--which must be stored as part of a string message in a "stock" exception may be assigned to a property. This may avoid random parsing issues if you actually do anything with the exceptions or try to trace through a particular event stream.
According to msdn:
To wrap an exception, you specify it as the inner exception of a new exception and then throw the new exception. This practice should be used only in situations where the original exception is not meaningful to the person who receives the exception, or the call stack for the exception is misleading or uninteresting.
Suppose method M1 is documented as throwing an exception of type X when some condition occurs. M1 calls method M2, which happens to throw an exception of type X which M1 is not prepared to handle. If M1 doesn't catch the exception from M2, the caller is unlikely to figure out that the exception thrown out of M1 isn't an X thrown by M1, but is instead an X thrown by M2, and its practical meaning and implications may be very different. Having M1 throw an exception of a type which will never be thrown by M2 may avoid this issue (though there could still be trouble if M2 could call M1 on some other object).

Is it a bad decision to introduce a method only for exception throwing?

i currenty thinking about a concept which should treat illegal states in my java program.
I have introduced a class which does processing steps on images.
public class ImageProcessor{
public Image processImage(Image img){
//do some processing steps
}
}
Now, I want to introduce another class which should check the the image before doing the processing.
public class ImageChecker{
public void checkImage(Image img) throws ImageNotProcessableException{
//for example, if the image has a width of 0 the full process
//should be broken, throw an exception
if (img.width=0) throw new ImageNotProcessableException("width is 0");
//other conditions throwing also exceptions
// the image is fine, do nothing
}
}
The two classes should be used in a Coordinator class.
public class Coordinator{
public void coordinate(Image img) throws ImageNotProcessableException{
//initialize both
imageChecker.checkImage(img); //if no exception is throw the process can run
imageprocessor.processImage(img);
}
}
The question is now, is this way of treating Exception (defining a separate method for them) a bad coding style? The idea for this design was to prevent polluting processing code with exception handling. I want the coordinator to throw exceptions and I thought this could be a senseful way. What do you think, is this a good way or is it an antipattern.
Thanks!
The validating method itself is a very good idea. You introduce very good separation of concerns - checking preconditions and validation in one place and actual processing in another.
However the usage is incorrect. The ImageProcessor should eagerly call ImageChecker.checkImage(). Otherwise the client of your library might forget to call it and pass invalid image.
Also *#Damien_The_Unbeliever* brings up a very good point about the structure of the code.
To make it as fancy as possible I would create an ImageProcessor interface with two implementations: one that performs the actual processing and a decorator implementation (ImageChecker) that performs validation and passes validated object to target ImageProcessor.
This way you can either use safe or fast (assuming validation is costly) implementation. Also in the future you might introduce other elements to the chain like caching or profiling.
This is not unreasonable. Although if checkImage exists for the sole purpose of checking whether it's ok to process an image and has no other return type, it would be reasonable to have it return a status code/object rather than throwing an Exception and returning void, e.g.,
ImageStatus status = checkImage(image);
if (status.isOk()) {
processImage(image);
}
This would be analogous to checking for divide by zero:
if (y != 0) {
z = x / y;
}
Checked exceptions generally are better for situations where you can't confirm a priori whether something will succeed or fail until you try it, e.g., IOException.
I see 3 questions here, and it's useful to separate them.
Should the caller see a class called "ImageProcessor", or a class called "Coordinator"?
Is it good to do validation of inputs in a separate method from the main processing?
Should this code use checked exceptions or unchecked exceptions?
My answers would be:
Use the prettier name for the classes or interfaces you are exposing. So, here "ImageProcessor" is much nicer than "Coordinator". ("Coordinator" sounds like an implementation detail you don't want to expose.)
This is an implementation decision. It's fine to separate some validation logic into a separate method if it makes things cleaner. But, you need to be careful of falling into a trap of thinking it is possible to anticipate upfront everything that can possibly go wrong in later stages of processing. The method that does the actual processing still needs to be free to throw exceptions so it can describe failures as accurately as possible, no matter what the initial quick validation decided. Also, you want to avoid writing the validation code in two places, since that is unnecessary code duplication. So, I'm a bit skeptical about having this separation, but I'd need to see the code. More likely, it's better to separate the actual image processing itself into various sub-tasks, and do the validation at the point you need it.
This is the age-old Java checked exceptions debate that will not go away in our lifetimes, and is impossible to summarize here. But, I think the consensus has fairly strongly shifted to favor using runtime exception rather than checked exception. Of course, legacy APIs still use checked exceptions. But for most new code, it's better to use runtime exceptions rather than checked exceptions, since this allows more robust code. (Checked exceptions have the annoying property of often being wrapped, rewrapped, swallowed, or otherwise mangled before they can get to the exception handler, and they cause lots of collateral damage along the way by making everyone's throws clause get longer.)

java.lang.Exception vs. rolling your own exception

At what point would you create your own exception class vs. using java.lang.Exception? (All the time? Only if it will be used outside the package? Only if it must contain advanced logic? etc...)
I think you need to ask yourself a slighly different question "What advantage does creating a new exception give me or developers who use my code?" Really the only advantage it gives you or other people is the ability to handle the exception. That seems like an obvious answer but really it's not. You should only be handling exceptions that you can reasonably recover from. If the exception you throw is a truly fatal error why give developers a chance to mis-handle it?
More in depth discussion: Custom exceptions: When should you create them?
Reason one:
Need to catch specific stuff. If calling code needs to deal with a specific exceptional condition, you need to differentiate your Exception, and Java differentiates exceptions with different types, so you need to write your own.
Basically, if someone has to write:
catch(ExistingException e) {
if({condition}) {
{ some stuff here}
}
else {
{ different stuff here}
}
}
You probably want to write a specific extension; catch Exception matching is clearer than conditionals, IMHO.
Remember: your new Exception can be a subclass of RuntimeException
Reason two:
API consolidation. If you write an interface and you have several implementations, it's possible that they will call different APIs with a whole bunch of different non-RuntimeExceptions thrown:
interface MyInterface {
void methodA();
}
class MyImplA {
void methodA() throws SQLException { ... }
}
class MyImplB {
void methodA() throws IOException { ... }
}
Do you really want MyInterface.methodA to throw SQLException and IOException? Maybe then it makes sense to wrap the possible exceptions in a custom Exception. Which again can be a RuntimeException. Or even RuntimeException itself...
I believe that:
catch (Exception e) {
...
}
... is an antipattern that should be avoided. You might want one centralized broad catch somewhere in your application, to log an error and prevent the whole application from terminating - but having them scattered around willy-nilly is bad.
Why:
try {
if(myShape.isHidden()) {
throw new Exception();
}
// More logic
} catch (Exception e) {
MyApp.notify("Can't munge a hidden shape");
}
So you try this, and due to a coding error, myShape is null. A NullPointerException gets thrown when the runtime tries to derefence myShape. This code reports a hidden shape, when it should be reporting a null pointer.
Either make your own exception, or find a suitably specialized exception in the API. It's not as if extending Exception or RuntimeException is onerous.
When I want to treat my exceptions differently from everybody else's. If I want to catch mine and propagate everyone else's, or if I want to catch someone else's and propagate mine, or if I want to catch both but treat them differently, then I will define a separate class for my exceptions. If I want to treat them all the same, either by propagating both or by catching both (and doing the same thing either way with the caught exceptions), the I will use the standard class.
IF there is an existing Exception with the language runtime or libraries, use it ELSE create your own, document it well and that should work in 99% of the cases.
Software captures meaning.
There are almost no reasons for throwing an existing exception: the JVM already does that for you. Your version of their exception isn't really accurate and throwing "Exception" isn't meaningful, either.
You might have a DataFormatException because of a parsing algorithm you wrote. This, however, is rare.
When your program encounters an exceptional situation, it's almost always unique to your program. Why force-fit your exceptional situation into an existing exception? If it's unique to your program, then... well... it's unique. Name it that way.
Do not, however, provide a unique exception class for each unique message. One exception class can have many variant messages and supporting details.
The Python rule of thumb, translated to Java, is to define any unique exceptions at the package level. [In Python, they suggest exceptions at the "module" level, something that doesn't precisely translate to Java.]
Start always by using the common exception classes and then when a need appears to handle it specially, change it.
When creating a method first time, just let exceptions go through.
If there are exceptions that must be handled, those can either be just defined in throws or wrapped to some runtime exception or wrapped own throws exception. I prefer runtime exceptions in many cases. Defining throws definition should be avoided until there is a need for it from API point of view.
Later when a need appears to do specific handling for an exception in some caller, come back and create new exception for it.
The point is to avoid doing extra work before knowing what is needed.
I can't imagine specifically throwing a java.lang.Exception if some object/class/method had a problem. It's too generic - if you're not going to create your own Exception class, seems to me like there ought to at least be a more specific Exception-type in the API.
I would use the exceptions from the Java API when the exception relates to the API. But if an exceptional situation arises that is unique to my own API then I will create an Exception for it. For example if I have a Range object with two properties min and max and the invariant min <= max then I will create an exception InvalidRangeException.
When I am writing code this helps because I know if the exception originates because I violated one of my own conditions or its something from the Java API.
In most cases it doesn't make sense to create your own exception class.
There is a tendency in novice programmers to create their own exception class just so they can use a name that is more indicative of the type of error. So you'll find classes like FTPInitializationException, DAOFactoryException etc. even though such exceptions are not being handled differently than standard exceptions. This is clearly an anti pattern that should be avoided.

Categories