why spring handles only unchecked exceptions - java

I want to know why spring handles only unchecked exceptions..... can any one explain what is the reason behind this .
Spring is using any design patterns which will avoid checked exceptions ?

Spring is using any design patterns which will avoid checked
exceptions ?
Not a design pattern but Best Practices for Exception Handling.
Consider below code:
public void consumeAndForgetAllExceptions(){
try {
...some code that throws exceptions
} catch (Exception ex){
ex.printStacktrace();
}
}
What is wrong with the code above?
Once an exception is thrown, normal program execution is suspended and control is transferred to the catch block. The catch block catches the exception and just suppresses it. Execution of the program continues after the catch block, as if nothing had happened.
How about the following?
public void someMethod() throws Exception{
}
This method is a blank one; it does not have any code in it. How can a blank method throw exceptions? Java does not stop you from doing this.
I want to know why spring handles only unchecked exceptions?
Personally I prefer unchecked exceptions declared in the throws cause. I hate having to catch exceptions when I'm not interested in them. I agree the spec needs to a few more exception types, but I disagree that they should be checked. Most frameworks rely on unchecked exceptions, not only Spring framework.
Best Practices for Designing the API
If the client can take some alternate action to recover from the exception, make it a checked exception.
If the client cannot do anything useful, then make the exception unchecked. By useful, I mean taking steps to recover from the exception and not just logging the exception.
The Java API has many unchecked exceptions,
such as
NullPointerException, IllegalArgumentException, and IllegalStateException. I prefer working with standard exceptions provided in Java rather than creating my own. They make my code easy to understand and avoid increasing the memory footprint of code.
See Also:
Unchecked Exceptions
Best practices in exception handling

Spring's central theme is Dependency Injection and IOC. Checked exceptions add unncessary code and create more dependency. As such, the dependency costs of checked exceptions outweigh their benefits. They reduce the ability to test code. They lead to lower cohesion and higher coupling. The goal of your code should be high cohesion and low coupling. Spring is focused towards the S.O.L.I.D principles of design.

Related

Handling exceptions in Java application

When I throw an exception from the package in which I handle the database, in the package in which I handle the UI, should I throw the same exception or create another?
The UI package should know the exceptions of the package which I handle the database?
We as programmers want to write quality code that solves problems. Unfortunately, exceptions come as side effects of our code. No one likes side effects, so we soon find our own ways to get around them. I have seen some smart programmers deal with exceptions the following way:
public void consumeAndForgetAllExceptions(){
try {
...some code that throws exceptions
} catch (Exception ex){
ex.printStacktrace();
}
}
What is wrong with the code above?
Once an exception is thrown, normal program execution is suspended and control is transferred to the catch block. The catch block catches the exception and just suppresses it. Execution of the program continues after the catch block, as if nothing had happened.
How about the following?
public void someMethod() throws Exception{
}
This method is a blank one; it does not have any code in it. How can a blank method throw exceptions? Java does not stop you from doing this. Recently, I came across similar code where the method was declared to throw exceptions, but there was no code that actually generated that exception. When I asked the programmer, he replied "I know, it is corrupting the API, but I am used to doing it and it works."
Please visit here for more details.
To keep your layers tightly coupled, I recommend to abstract your Exceptions (if there isn't a fitting standard exception). With abstract I mean that you could wrap database-dependent exceptions like SQLException into a PersistenceException or sth. like that. This way you can easily change your layers without having to worry about changing code of the layers above.
You should then only catch and handle the exception if you can handle them, e.g. propagate it to the user in you GUI. Otherwise you should throw them to the next caller, until it is handled on a higher level.
You should avoid recreating new exceptions on their way up, that wouldn't add any information in most cases.
You should throw an Exception that makes sense. More importantly you should not throw an exception that doesn't. Exceptions represent error states that you cannot easily recover from, meaning that if you have code to handle things like missing files, it should not throw an exception. You should only throw an exception when something unexpected happens.
As exceptions propagate up through your stack, they should be diversified, depending on what part of the code they where caught in.
For instance your persistence framework may throw an SqlException, your DAO Layer may re-throwthis as an IllegalArgumentExection, or ObjectNotFoundEception, your Service Layer may throw a MalformedRequestException, an AccessDeniedException or a DeviceNotEnrolledException. Lastly your UI may display this to the user in any number of meaningful ways.
I recommend putting the exceptions where it relates the most. You should have different exceptions that handle the code in different types of situations. The UI is going to have different types of exceptions it should handle than the database.
Use pre-defined exceptions where it makes sense, you could also make your own exceptions and put them in both packages if need be.
Design it so that the code can be handled in a way where the catch statement is easy to logically locate and the catch statement handles the code and can do some sort of recovery after being passed up the hierarchy.
The type of situation we are concerned with the most are checked exceptions. These are problems that we can anticipate and catch and try to make a recovery. Make sure you aren't using too many of these! They are costly to resources!

Is it a good practice to use nested exceptions?

This is probably a broad question, not quite SO style, but I'd still like to get some hints or guidelines if possible.
I've been looking through some legacy code and found a part of it that has methods with exceptions nested 3 or 4 levels down.
Is this considered to be a normal practice or should one avoid such codestyle where possible? If it should be avoided, what are the negative effects besides the increasing costs of exception handling and decreasing readability? Are there common ways of refactoring the code to avoid this?
I personally prefer the following ideology
Wrap Alien Exceptions
An "alien" exception is an exception thrown by a Java API or a third party library. In other words, an exception you do not control.
Its better to catch all alien exceptions and wrap them in an appropriate application specific exception. Once the alien exception is converted to your own exception, you can propagate that exception any way you like.
Rethrowing Checked Exceptions can get Messy
If your application uses checked exceptions, rethrowing the original exception means that the method rethrowing it must also declare it.
The closer you get to the top of the call hierarchy, the more exceptions will be declared thrown. Unless you just declare all your methods to throw Exception. However, if you do so you might as well use unchecked exceptions, since you are not really getting any benefit from the compiler exception checking anyways.
This is why I prefer to catch non-application specific exceptions and wrap them in an application specific exception, before propagating them up the call stack.
Guidelines For Wrapping : The context in which an exception occurs may be just as important as the location of the exception itself. A given location in the application may be reachable via different execution paths, and the execution path may influence the severity and cause of the error, if it occurs.
If you need to add context information to an exception as you propagate it up the call stack, you need to use active propagation. In other words, you need to catch the exception in various relevant locations on the way up the call stack, and add the relevant context information to it, before rethrowing or wrapping it.
public void doSomething() throws SomeException{
try{
doSomethingThatCanThrowException();
} catch (SomeException e){
e.addContextInformation(“more info”);
throw e; //throw e, or wrap it – see next line.
//throw new WrappingException(e, “more information”);
} finally {
//clean up – close open resources etc.
}
}
Checked Exceptions should not be propagated up the stack or chained if possible. If a method is throwing a checked Exception its caller is supposed to handle it, if caller is not handling it and propagating it to its caller, then overall complexity increases.
In a three layered example : Dao , Service , Controller
DAO layer will throw DAOException
Service layer should not expose DAOException to Controller , instead it should be throwing relevant BuinessExceptions, which the Controller should be handling.
Exception handling tends to be an expensive way to handle flow control (certainly for C# and Java).
The runtime does quite a lot of work when an exception object is constructed - getting the stack trace together, figuring out where the exception is handled and more.
All this costs in memory and CPU resources that do not need to be expanded if flow control statements are used for flow control.
Additionally, there is a semantic issue. Exceptions are for exceptional situations, not for normal flow control. One should use exception handling for handling unanticipated/exceptional situations, not as normal program flow, because otherwise, an uncaught exception will tell you much less.
Apart from these two, there is the matter of others reading the code. Using exceptions in such a manner is not something most programmers will expect, so readability and how understandable your code is suffer. When one sees "Exception", one thinks - something bad happened, something that is not supposed to happen normally. So, using exceptions in this manner is just plain confusing.
Please take a look at below links
Exception Handling: Common Problems and Best Practice with Java 1.4 - pdf
Why not use exceptions as regular flow of control?
Best Practices for Exception Handling
Error Handling
Mr. Google Links
I've been looking through some legacy code and found a part of it that has methods with exceptions nested 3 or 4 levels down.
Is this considered to be a normal practice or should one avoid such codestyle where possible?
This is not a necessary process to handle your exception in this way, as it will increase your application overhead, until you really need to handle very specific exception(checked or Alien Exceptions) and you can ignore overhead to get specific information to handle that exception.
If it should be avoided, what are the negative effects besides the increasing costs of exception handling and decreasing readability?
As I mentioned you will not get specific information about the exception, if you are not going to use nested exception handling(throws with some added information to the upper handler) you may/may'not do specific action on behalf of some tough exception, but in nested case you can do action by handling that specific situation.
Are there common ways of refactoring the code to avoid this?
If you have a poorly factored program that does what the you want and has no serious bugs, for god sake leave it alone! When you need to fix a bug or add a feature, you Refactor Mercilessly the code that you encounter in your efforts. Override the Exception Class in your custom Exception Handler and add some added features to handle your problem.
The overriding method must NOT throw checked exceptions that are new or broader than those declared by the overridden method. For example, a method that declares a FileNotFoundException cannot be overridden by a method that declares a SQLException, Exception, or any other non-runtime exception unless it's a subclass of FileNotFoundException.
Hop this will help you.
You should do away with the exception nesting. You should either avoid chaining the exceptions in the first place, or (selectively) unwrap and then rethrow the nested exceptions further up the stack.
About handling legacy code I would recommend you have a look at the book covering the topic:
http://www.amazon.com/Working-Effectively-Legacy-Michael-Feathers/dp/0131177052
You dont even have to go through the whole book, just look at the things that concern you at the moment.
Also a good book regarding good practices is:
http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882/ref=sr_1_1?s=books&ie=UTF8&qid=1356340809&sr=1-1&keywords=clean+code
The best approach when handling nested exceptions is refactoring the code and using runtime instead of checked exceptions, and handling those where needed. This way the code is more readable and easier to maintain.
Its depend on the Business logic. You may take action on the exception there itself or you may propogate it all the way upto caller and leave it to the caller for what action he want.
e.g. There are lot of third party API where they don't handle the exception but they throw it from method and hence facilitate API users to take actions as per their need.
e.q. oracle JDBC driver. Driver.getConnection() throws exception. Now caller/API user can handle it as per their need. One may just print stack trace, one may notify admin asking for his attention or one may choose just silently exit the application.
There are two approaches:
To generate a separate exception for each event.
To create a generic exception and describe what caused it
The first approach allows you to write different code for handling the different events, but it requires you to write lot of Exception classes and in some case it could be just too much.
The second approach is more concise, but it makes it difficult to handle the different situations.
As it happens very often in programming the best solution is in the middle, where you balance generating separate exceptions and using one exception for other cases.
The rule of the thumb in this case could be to generate a separate Exception class for the exceptions you want to handle specifically with separate code.
Similarly to the what to throw, we should also have control on what to catch. We can use two approaches for our catch blocks:
A single catch block for all. For example:
catch (Throwable e) {
throw new CommandExecutorException(e);
}
many catch blocks one for each Exception. For example:
} catch (ClassCastException e1) {
...
} catch (FileNotFoundException e) {
...
} catch (IOException e) {
...
}
The first approach is very compact but basically groups every exception in the same case, it's useful only in the situation where all the exceptions are managed equally and do the same thing.
This approach is generally discouraged as it gives no control on the exceptions being catched, leading sometimes to tough bugs, which are also hard to find.
The second approach requires more lines of code but you can execute different operations depending on the exception occurred. This approach is more flexible but in some cases leads your methods to be very long due to exception handling.

Java Exceptions, What to catch and what not to?

I keep getting the dreaded java.something.someException errors while running my java app. and I don't seem to be getting the hang of what exceptions to handle and what not to?
When I read the api docs most of the functions throw exceptions like if I use I/O or use an Array... etc.
How to make a decision about what exceptions to catch and what not to and based on what parameters?
I am talking about checked exceptions here.
Short answer
Catch exceptions that you can deal with then and there, re-throw what you can't.
Long answer
It's called exception-handling code for a reason: whenever you are tempted to write a catch block, you need to have a good reason to catch the exception in the first place. A catch block is stating your intent to catch the exception, and then do something about it. Examples of doing something about it include, but are not limited to:
Retrying the operation that threw the exception. This can make sense in the case of IOException's and other issues that may be temporary (i.e. a network error in the middle of trying to upload a file to a server. Maybe your code should retry the upload a few times).
Logging the exception. Yes, logging counts as doing something. You might also want to re-throw the original exception after logging it so that other code still has a chance to deal with the exception, but that depends on the situation.
Wrapping the exception in another exception that is more appropriate for your class's interface. For example, if you have a FileUploader class, you could wrap IOException's in a more generic UploadFailedException so that classes using your class don't have to have detailed knowledge of how your upload code works (the fact that it throws an IOException is technically an implementation detail).
If the code can't reasonably do anything about the problem at the point where it occurs, then you shouldn't catch it at all.
Unfortunately, such hard-and-fast rules never work 100% of the time. Sometimes, a third-party library you are using will throw checked exceptions that you really don't care about or which will never actually happen. In these cases, you can get away with using an empty catch block that doesn't run any code, but this is not a recommended way to deal with exceptions. At the very least, you should add a comment explaining why you are ignoring the exception (but as CPerkins notes in the comments, "never say never". You may want to actually log these kinds of "never-going-to-happen" exceptions, so just in case such an exception does happen, you are aware of it and can investigate further).
Still, the general rule is, if the method you are in can't do something reasonable with an exception (log it, rethrow it, retry the operation, etc.) then you shouldn't write a catch block at all. Let the calling method deal with the exception. If you are dealing with checked exceptions, add the checked exception to the throws clause of your method, which tells the compiler to pass the exception upwards to the calling method, which may be better suited to handle the error (the calling method may have more context, so it might have a better idea of how to handle the exception).
Usually, it is good to put a try...catch in your main method, which will catch any exceptions that your code couldn't deal with, and report this information to the user and exit the application gracefully.
And finally, don't forget about finally
Also keep in mind that even if you don't write a catch block, you might still need to write a finally block, if you need clean-up code to run regardless of whether the operation you are trying to perform throws an exception or not. A common example is opening up a file in the try block: you'll still want to close the file, even if an exception occurs, and even if your method isn't going to catch the exception. In fact, another common rule of thumb that you might see in tutorials and books is that try...finally blocks should be more common that try...catch blocks in your code, precisely because catch blocks should only be written when you can actually handle the exception, but finally blocks are needed whenever your code needs to clean up after itself.
I highly recommend chapter 9 (Exceptions) in Joshua Bloch's Effective Java, 2nd Edition for these questions.
A general rule of thumb is to handle those exceptions that you can do something about and don't handle those that you can't. In the cases where you don't handle an exception the caller is expected to handle them. If you're writing a framework or a library usually you'll end up wrapping low level exceptions like SQLException in a library or framework specific exception to abstract away the lower level details.
For example, if you're writing a method that writes to a file on disk then you should probably handle FileNotFoundExceptions since you can create the missing file, but if you run into problems creating the file or writing to it then you should probably let the caller handle it (after performing whatever cleanup work needs to be done).
These are my personal findings:
You need a try {} catch (Throwable o) {...} in your main routine so any unexpected exception can be caught, logged and the user told.
Checked exceptions are checked because you need as a programmer to make a decision what to do when they happen. Remember, one decision might be just to say "ok, time to crash".
If you end up with a fatal situation with a checked exception where all you can do is crash, then "throw new RuntimeException("reason", checkedException);" so the handler above have something to log. Include value of important local variables - remember some day you will have to debug a situation where the only thing you have is the stack trace.
Never, ever catch an exception and just ignore it. If you have to then you must document why you are allowed to break the rule, and do it right there, in the catch block.
And a hint that will help you some day: When you crash, provide a simple means to let the user seeing the message email the stack trace to you.
EDIT: Do not be afraid to create new exceptions if the ones available does not completely cover what you need. This allows you to get better naming in stack traces and your error handling code can differentiate between different cases easily. You may want to base all your own exceptions on a common base class ("OurDomainException") so you can use the base class in catch clauses to see if what type it is.
Having coded in Java for a few years, I agree that it is easy to get annoyed by writing endless try-catch blocks.
A good way of coding fast is to catch specific exceptions in as low level as you can, and catch the base Exception at the outermost level (in main()) just so that you can write a generic error message instead of letting the program crash.
This lets you have a running code pretty fast, and then you can take your time to add specific exceptions in various layers with their handling logic.
Catch checked Exception, do not catch RuntimeException. Try to catch specific Exception, try not to catch by generic java.lang.Exception.
Module boundaries
I catch exceptions for cleaner module boundaries, too. For example if there is a SQLException thrown that I can't handle I'll catch it nevertheless and throw my own descriptive exception instead (putting the SQLException as cause). This way the caller doesn't have to know that I'm using a database to fulfill his request. He just gets an error "Cannot handle this specific use case". If I decide to fulfill his request without database access, I don't have to change my API.
As a rule of thumb I catch exceptions where I will be able to do something with then, or where I want the exception to stop moving up. For example, if I am processing a list of items, and I want the next item to be processed even if the others fail, then I will put a try...catch block around that item processing and only in there. I usually put a try...catch(Throwable) in the main method of my program so I can log errors like a class not found or similar stuff.
I don't put a try...catch block in a method if I will not know what to do with that exception. If you do, you will just bloat your code with lots of exception handling code.

Why does Java have both checked and unchecked exceptions? [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
When to choose checked and unchecked exceptions
Why does Java as a language have both checked and unchecked exceptions. What purpose do they serve?
Note: I'm not asking when I should use them, or how to code them, but what they add to the language.
The theory for checked exceptions is simple.
When designing an interface, think of exceptional cases that can occur, and will occur, with the normal state of a method call. Declare these exceptions in your interface, as the programmer will have to handle them directly.
For example, a bank account withdraw method may declare an OverdraftException, which is an expected exception - a withdrawal may fail due to overdraft, but this type of failure may be handled differently by the client code (one may decide to completely deny the withdrawal, another may decide to apply a huge penalty and allow for a negative balance to be recorded, another may decide that their client is allowed to draw from a different account).
However, runtime exceptions were supposed to be programming errors that weren't supposed to be handled directly - such as NullPointerExceptions, which only occur if methods take invalid arguments or don't check for such cases directly.
This is a good theory. However, Java messed up with its implementation of Exceptions, and this threw the book of this theory out the window.
There are two cases that I will illustrate where Java messed up with its implementation of Exceptions. These are IOException and SQLException.
An IOException occurs anytime, anywhere a stream in the IO libraries of Java messes up. This is a checked exception, however. But, generally you cannot do anything but log that an error occur - if you're simply writing to the console, what can you reasonably be expected to do if you suddenly get an IOException when you're writing to it?
But there's more.
IOException also hides stuff like file exceptions and network exceptions. They may be subclasses of IOException floating around for that, but it is still a checked exception. If your writing to an external file fails, you can't really do much about it - if your network connection is severed, ditto.
SQLException is the same way. Exception names should show what happened when they are called. SQLException does not. SQLException is thrown any single time any possible number of errors are encountered when dealing with a database - MOST OF WHICH THAT HAVE NOTHING TO DO WITH SQL.
Therefore, programmers typically get annoyed with handling exceptions, and let Eclipse (or whatever IDE they're using) generate blocks like this:
try {
thisMethodThrowsACheckedExceptionButIDontCare();
}
catch(Exception e) {
e.printStackTrace();
}
However, with RuntimeExceptions, these intentionally bubble up and eventually get handled by the JVM or container level. This is a good thing - it forces errors to show up and then you must fix the code directly instead of ignoring the exception - you may still end up just printing the stack trace (hopefully logging it instead of printing to the console directly), but then there will be an exception handler that you were forced to write because of a real problem - not because a method said that it might possibly throw an Exception, but that it did.
Spring uses a DataAccessException to wrap SQLExceptions so that you don't have to handle them as a checked exception. It makes code much cleaner as a result - if you expect a DataAccessException, you can handle it - but most of the time you let it propagate and be logged as an error, because your SQL should be debugged by the time you release your application, meaning the DataAccessException is probably a hardware issue that you could not resolve - DataAccessException is a much more meaningful name than SQLException, because it shows that access to data failed - not that your SQL query was nessecarily at fault.
They add a differentiation between errors that the designer of a library feels must be caught, and ones that they feel the programmer shouldn't handle.
For example it might be reasonable for a program to handle bad input from a user, but if something goes wrong with the underlying OS and threads starts to die without reason, it isn't something that the program should be expected to handle.
Personally, I think checked exceptions were a mistake in Java.
That aside, designating both checked and unchecked exceptions allows a library to differentiate between recoverable and unrecoverable errors. By making all recoverable errors throw checked exceptions, a library/language can force a developer to handle the edge cases they might otherwise paper over.
The big problem with this:
try{
myCode();
}catch(Exception e){ //Do nothing }
Additionally, in most cases it really is best to just throw up your hands and pass an exception up when one occurs. By forcing checked exceptions to be declared, a method that really doesn't care if an error occurs ends up having dependencies (in terms of compatibility, but also code-smell and others) it really shouldn't.
I think Sun initially thought it would be a good idea because the programmer is forced to handle the exception. However, many years later, pretty much everyone agrees they are a bad, unneccessary addition.
One of the main issues (apart from cluttering code) is that they leak abstractions form lower layers to higher layers (such as rmi remote exceptions)
Checked and unchecked exceptions invokes a bit of a religious argument - Java fell one side of the fence, C# the other.
In Java checked exceptions should be used when the calling code can recover from the error as where unchecked exceptions are used when there's a critical error (with perhaps the exception - no pun intended - of NullPointerException) that the calling code is unlikely to be able to recover from.
Personally I like to have both available to me generally favouring checked exceptions because they allow me to force the calling code to deal with an error situation that a developer might otherwise have ignored (although the infamous empty catch block side-steps this).
I don't think there's anything at all conceptually wrong with checked exceptions... but they do tend to suck mightilly in practice, because (especially early) library developers over-use them.
Also the "catch or declare" requirement does NOT fit well with interfaces.
My basics thoughts are: "Stuff that goes wrong" comes in two basic flavours: recoverable, and unrecoverable... Ergo: Business Exceptions and System Errors.
For instance: What do you (the library developer) expect me (the application programmer) to do about recovering from a failure in a call to SomeStream.close()? Yes, I definately need to be made aware that something has gone horribly wrong, but really my only option is to terminate the program/request/process/thread which tripped over it. I cannot be reasonably expected to even attempt to recover from the situation... Ergo: It's an uncoverable error, and therefore I shouldn't be forced to write a lot of highly repitious boilerplate catch-blocks which don't handle the problem at every level of the (potentially very deep) callstack. Therefore I believe it would be better if "catch all" checked exceptions such as IOException had never been invented... CloseException extends UncheckedIOException would be more appropriate, IMHO.
Also, if I had a time machine I'd go back in time and plead with the Java gods for:
interface Throwable
abstract class Exception
abstract class CheckedException
abstract class UncheckedException
class Error
Also: I'd love to see a #FaultBarrier class-annotation, which makes the compiler enforce: All exceptions (especially unchecked ones) must be caught or explicitly thrown. The most horribilest hunk of system I've ever worked on was riddled with throwings of raw RuntimeException; It's enough to make you weep.
Cheers. Keith.

Why throwing an EJBException is a "recommended" practice?

I keep getting this "suggestion" from many fellow developers over and over again. In my experience I've found that EJBExceptions are well-suited for "end of the world" from the bean instance perspective (like when something is so wrong that the bean instance cannot recover by itself). If an instance can recover, I think it's better to throw an application exception.
Here is the pattern that I meet over and over again:
private SomeResource resource;
ejbCreate:
resource = allocateResource(...);
omMessage:
try {
...
} catch (JMSException e) {
throw new EJBException(e);
}
ejbRemove:
freeResource(resource);
IMHO this is a antipattern that causes resource leaks.
EDIT: Specifically, the EJB specification says that if a bean throws a runtime exception (and EJBException is a runtime exception) from the business method, then the bean is discarded without calling ejbRemove on it.
Is this a relevant example against throwing an EJBException?
What are the relevant cases when EJBException should be thrown?
The throwing of EJBException is recommended by the EJB spec (14.2.2 in the EJB 3) in the cases where the EJB cannot recover from an exception it encounters. The spec also says that the EJB can reasonably allow (unchecked) System Exceptions to propagate to the container.
I agree with your reading of the spec that in such cases life-cycle callback methods will not be invoked by the container, and hence your concern that any resource-tidy up that would normally happen in the ejbRemove() callback will not happen and so there's a danger of resource leakage.
My experience is that very many tricky problems arise because of a lack of defensive coding. "Situation X cannot occur in a well behaved system, and if it does then the whole system is broken, so I'll not code for that eventuality." Then we get some "interesting" alignment of the stars and operator errors and the "can't happen" happens several times in quick succession and unanticipated side-effects kick in leading to really difficult to diagnose problems.
Hence I would say:
Do everything you can to leave the Bean instance in a state where the next invocation of a business method might be able to work. This might mean catching exceptions and closing resources that are in error. In this case you may then chose to tell the callers, "sorry guv, that request didn't work, but maybe if you retry later ..." I do that by throwing a TransientException checked exception.
If you have no important housekeeping in ejbRemove then you can allow SystemExceptions to propogate - but I'm not sure that this is friendly. You depend upon a library and it throws a NullPointerException. Is is actually more robust to catch and rethrow TransientException?
If you do have important housekeeping, then I think you do need to catch all exceptions and at least attempt the cleanup. You may then choose to rethrow EJBException or a system exception so that the instance is destroyed, but at least you've tried to do the housekeeping.
The container can still commit the current transaction even though the EJB method has thrown an application exception. If your EJB method can throw an application exception then you should consider using EJBContext.setRollbackOnly() like this:
public void method() throws ApplicationException {
try {
...
} catch (ApplicationException e) {
_context.setRollbackOnly();
throw e;
}
}
Throwing an EJBException or a system (unchecked) exception means that the container will automatically rollback the transaction. See: http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/Transaction3.html
If your system's EJBs do not routinely trap and handle application exceptions then code that throws them can result in a partially complete operation committing its changes.
This can lead to hard-to-find bugs because the "user myth" of an EJB method with CMP is that it maps to a transaction, which is atomic. The partially complete business logic is atomically committed to the database. This is extremely confusing when it happens in practice. Joel's article on leaky abstractions: http://www.joelonsoftware.com/articles/LeakyAbstractions.html explains why.
If your system has EJBs that do not handle application exceptions correctly the logical answer is to fix them so that they do. Until the problem is fixed, your team might have a rational reason for not wanting application exceptions thrown from EJBs.
Whether or not is leaks resources depends on how those resources are administered. The discarded bean gets garbage collected giving up its reference to the resource which gets garbage collected in turn when no more references point to it. If the resource is also kept in a collection with a path to root, it will leak unless the container has a pool manager that can detect idle resources and recycle it.
I agree with you that the bean should handle any exceptions it can by itself and let the result be known to the caller. For me the anti pattern in the situation you describe is using exceptions to pass object state. Exceptions should be exceptions, not used as return values.

Categories