Spring transaction and try catch blocks - java

I am pretty new to Kotlin and Spring and had a very basic doubt. Consider a function like this:
#transaction
fun accept() {
try {
write to table A
throw Exception()
} catch(){
write to table B
}
}
Question: I understand that Table B write will be successful, but will the table A write succeed? and why?
Any pointers to

Spring has a bit of a bizarre take on what exceptions 'mean'. It acts as follows. A transaction method doesn't commit anything until it exits. i.e. this:
#transaction
fun accept() {
write to table A
while (true) {} // loop forever
}
trivially never actually commits anything, that's probably obvious. Otherwise, the method exits, and it can exit in one of three ways:
The method 'returns'. As in, no exception is thrown out of the method - exceptions might be thrown, but they are caught. Then upon exiting the method, the transaction is committed. Note that this describes your snippet - which does not throw an exception out of the method. Hence, the write to table A and B will both happen and be visible from outside parties!
The method finishes by throwing an UNCHECKED exception. Spring's opinion is that this is 'unexpected', and indicates the result of executing the method is failure - the entire transaction is aborted. the write to table A will not be visible to other transactions, ever, nor would the write to table B (let's imagine that after the catch block, you have throw new RuntimeException(), which is unchecked).
The method ends by throwing a CHECKED exception out. Spring's opinion is that this must mean that it is 'intentional', and indicates that the code succeeded; it simply chose to "return" an exception instead of finishing up normally. The transaction is committed - the write to table A will be visible to others. The write to table B will also be visible to others (this is assuming that you add throw new IOException() to the end of your accept method, and of course that your method is allowed to do that. Which in java means it has to be declared as void accept() throws IOException {}, of course.
The notion of checked and unchecked does not exist in kotlin - in kotlin, all exceptions are 'unchecked', effectively. However, spring doesn't go: "OOoooohhhh, kotlin user, I'll just treat everything as if it was unchecked, i.e. any exceptions thrown result in a aborted transaction". Nope, so, you must learn what checked exceptions are even if you write only kotlin.
Unchecked exceptions are all throwables that have in their type hierarchy either java.lang.Error (such as java.lang.InternalError, which extends j.l.Error), or java.lang.RuntimeException, such as NullPointerException.
All other throwables are 'checked'. Such as IOException, which extends Exception. which extends Throwable. Exception itself is checked.
NB: You can add interceptors and the like to change this behaviour; "checked exception means we need to commit, checked means we need to abort" is merely the default behaviour.

If "write to table A" is successful then yes it will persist.
Why? Because transaction demarcation is done by interceptors that act upon exceptions and in your code no interceptor would see that exception as they could only be executed around those "write to table X" calls (if those are done via interceptable code) or accept().
Let me try to add some more details:
In general, you can conceptually think of the interceptor looking like this (they look different but the example is used to illustrate the point - I'll also use Java code because I'm not that familiar with Kotlin):
void runInTransaction(Runnable interceptedCode) {
Transaction tx = startTransaction();
try {
interceptedCode.run();
tx.commit();
} catch( Exception e) { //kept simple for illustration purposes, in reality this is way more complex
tx.rollback();
}
}
Then you'd call it like this:
runInTransaction(() -> accept());
As you can see, since the exception is only thrown and caught in accept() - and thus won't leave the method - the interceptor won't even see it and thus will commit the transaction.

Related

How can I pass a collection of exceptions as a root cause?

Some method, myMethod, invokes several parallel executions and awaits their terminations.
These parallel executions can finish with exceptions. So myMethod gets an exception list.
I want to pass the exception list as a root cause, but the root cause might be only a single exception. Sure I can create my own exception to achieve what I want, but I want to know if Java, Spring, or Spring Batch has something like this out of the box.
I'm not sure I'd do it (though given the JavaDoc I couldn't tell you why I hesitate), but there is the list of suppressed exceptions on Throwable, which you can add to via addSuppressed. The JavaDoc doesn't seem to say this is only for the JVM to use in try-with-resources:
Appends the specified exception to the exceptions that were suppressed in order to deliver this exception. This method is thread-safe and typically called (automatically and implicitly) by the try-with-resources statement.
The suppression behavior is enabled unless disabled via a constructor. When suppression is disabled, this method does nothing other than to validate its argument.
Note that when one exception causes another exception, the first exception is usually caught and then the second exception is thrown in response. In other words, there is a causal connection between the two exceptions. In contrast, there are situations where two independent exceptions can be thrown in sibling code blocks, in particular in the try block of a try-with-resources statement and the compiler-generated finally block which closes the resource. In these situations, only one of the thrown exceptions can be propagated. In the try-with-resources statement, when there are two such exceptions, the exception originating from the try block is propagated and the exception from the finally block is added to the list of exceptions suppressed by the exception from the try block. As an exception unwinds the stack, it can accumulate multiple suppressed exceptions.
An exception may have suppressed exceptions while also being caused by another exception. Whether or not an exception has a cause is semantically known at the time of its creation, unlike whether or not an exception will suppress other exceptions which is typically only determined after an exception is thrown.
Note that programmer written code is also able to take advantage of calling this method in situations where there are multiple sibling exceptions and only one can be propagated.
Note that last paragraph, which seems to suit your case.
Exceptions and their causes are always only a 1:1 thing: you can throw one exception and each exception can only have one cause (which can again have one cause ...).
That could be considered a design fault, especially when considering multi-threaded behaviour as you described.
That's one of the reasons why Java 7 added addSuppressed to throwable which can basically attach an arbitrary amount of exceptions to a single other one (the other primary motivation was try-with-resources which needed a way to handle exceptions in the finally block without silently dropping them).
So basically when you have 1 exception that causes your process to fail, you add that one as the cause of your higher-level exception, and if you have any more, then you add those to the original one using addSuppressed. The idea is that that first exception "supressed" the others becoming a member of the "real exception chain".
Sample code:
Exception exception = null;
for (Foobar foobar : foobars) {
try {
foobar.frobnicate();
} catch (Exception ex) {
if (exception == null) {
exception = ex;
} else {
exception.addSuppressed(ex);
}
}
}
if (exception != null) {
throw new SomethingWentWrongException(exception);
}

call stack: catch vs. throws

When to use "catch" and when to use "throws"?
try {
//stuff
}
catch (MyException me) {
//stuff
}
versus
public void doSomething() throws MyException {
//stuff
}
In the case of "throws", where to place my catch along the call stack?
Main
----- Function 1
----- Function 2
----- Function 3 (generate exception)
If I propagate the exception from function 3 to function 2, why shouldn't function 2 do the same? So at the end I would end up managing all the exceptions in the "main" and I think it's not a go0d practice to put all the code inside a try block, isn't it?
So what's the logical way to choose between "catch" and "throws"? And in the second case, where should I place my catch in the call stack?
They're basically inverse of each other. throws means that a function is allowed to throw an exception; catch means that a block (the try) block expects that an exception might get thrown, and is prepared to handle it.
To take the ball metaphor, a pitcher throws an exception that the catcher expects. The catcher catches the ball and handles it somehow. (Well, maybe the metaphor is a bit off, since the catcher usually handles the ball by throwing it back to the pitcher. :) ) Here, the pitcher is a method, and the catcher is a try-catch-[finally] block.
You should declare that a method throws a checked exception whenever it's necessary for the method's caller to catch it or pass it on. You should catch an exception whenever you are ready to handle that exception right then and there.
For example, if you're writing a program with a graphical interface that also has a core that reads from a file, the core classes are unequipped to tell the user there was an error, that's the graphical interface's job. So methods such as getSomethingFromFile() in a core program might throw IOException. If the graphical interface calls getSomethingFromFile() and determines there's a read error, the graphical interface can then display a dialog to the user, so it is ready then and there to catch the exception. In this case, the getSomethingFromFile() call should be enclosed in try/catch.
If you're going for a throw - catch approach to handle errors, then the actual error handling must be done by the component with the responsibility of doing so, in particular because this allows you to encapsulate the logic where it belongs.
The exception is catched by a certain class who knows what to do with it, and the course of action that must be taken. In some particular cases you can rethrow an exception by wrapping it in another one (setting the exception as its cause). Take any ORM as an example, any low level exception is wrapped in, for example, a PersistenceException that can have a SQLSyntaxException as its cause.
throws comes into play if you don't have the proper tools to manage the exception in a certain context and you want to propagate it to a higher layer/tier where it can be properly managed.
Let me put a "big picture example":
Save entity to database
Communication error
Exception is thrown, so your persistence object must handle it.
You catch it, wrap it and rethrow it as one of your own exceptions (I'm against letting persistence exceptions propagate to higher layers... but that's just me).
the persistence throws an exception that's catched by the model.
The model retries the operation.
Another failure (same wrap + throw).
The model notifies the failure and elevates a report to the view. This is what I meant by being catched by the one who "knows" what to do.
The view displays "No saving today, sorry" to the user.
The example contains both throw and catch cases, I hope it helps to clarify.

Throwing a new exception while throwing an old exception

If a destructor throws in C++ during stack unwinding caused by an exception, the program terminates. (That's why destructors should never throw in C++.) Example:
struct Foo
{
~Foo()
{
throw 2; // whoops, already throwing 1 at this point, let's terminate!
}
};
int main()
{
Foo foo;
throw 1;
}
terminate called after throwing an instance of 'int'
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
If a finally block is entered in Java because of an exception in the corresponding try block and that finally block throws a second exception, the first exception is silently swallowed. Example:
public static void foo() throws Exception
{
try
{
throw new Exception("first");
}
finally
{
throw new Exception("second");
}
}
public static void main(String[] args)
{
try
{
foo();
}
catch (Exception e)
{
System.out.println(e.getMessage()); // prints "second"
}
}
This question crossed my mind: Could a programming language handle multiple exceptions being thrown at the same time? Would that be useful? Have you ever missed that ability? Is there a language that already supports this? Is there any experience with such an approach?
Any thoughts?
Think in terms of flow control. Exceptions are fundamentally just fancy setjmp/longjmp or setcc/callcc anyway. The exception object is used to select a particular place to jump to, like an address. The exception handler simply recurses on the current exception, longjmping until it is handled.
Handling two exceptions at a time is simply a matter of bundling them together into one, such that the result produces coherent flow control. I can think of two alternatives:
Combine them into an uncatchable exception. It would amount to unwinding the entire stack and ignoring all handlers. This creates the risk of an exception cascade causing totally random behavior.
Somehow construct their Cartesian product. Yeah, right.
The C++ methodology serves the interest of predictability well.
You can chain exceptions. http://java.sun.com/docs/books/tutorial/essential/exceptions/chained.html
try {
} catch (IOException e) {
throw new SampleException("Other IOException", e);
}
You can also have a try catch inside your finnally too.
try{
}catch(Exception e){
}finally{
try{
throw new SampleException("foo");
}catch(Exception e){
}
}
Edit:
Also you can have multiple catches.
I don't think multiple exceptions would be a good idea, because an exception is already something you need to recover from. The only reason to have more than one exception I can think of is if you use it as part of your logic (like multiple returns), wich would be deviating from the original purpose of the idea of the Exception.
Besides, how can you produce two exceptions at the same time?
Could a programming language handle multiple exceptions? Sure, I don't see why not. Would this be useful? No, I would say it would not be. Error handling and resumption is very hard as it is - I don't see how adding combinatorial explosion to the problem would help things.
Yes, it is possible for a language to support throwing multiple exceptions at a time; however, that also means that programmers need to handle multiple exceptions at a time as well, so there is definitely a tradeoff. I have heard of languages that have this although I am having trouble coming up with the list off the top of my head; I believe LINQ or PLINQ may be one of those languages, but I don't quite remember. Anyway, there are different ways that multiple exceptions can be thrown... one way is to use exception chaining, either by forcing one exception to become the "cause" or "previouslyProgatingException" of the other, or to bottle all of the exceptions up into a single exception representing the fact that multiple exceptions have been thrown. I suppose a language could also introduce a catch clause that lets you specify multiple exception types at once, although that would be a poor design choice, IMHO, as the number of handlers is large enough as is, and that would result in an explosion of catch clauses just to handle every single possible combination.
C++ std::exception_ptr allows you store exceptions. So it should be possible to embed exceptions in other exceptions and give you the impression that you have the stack on thrown exceptions. This could be useful if you want to know the root cause of the actual exception.
One situation where multiple thrown exceptions in parallel might be useful, is unit testing with JUnit:
If a test fails, an exception is thrown (either produced by code under test or an assertion).
Each #After method is invoked after the test, whether the test fails or succeeds.
If an After method fails, another exception is thrown.
Only the exception thrown in the After method is displayed in my IDE (Eclipse) for the test result.
I know that JUnit notifies its test listeners about both exceptions, and when debugging a test in Eclipse I can see the first exception appearing in the JUnit view, only to be replaced by the second exception shortly after.
This problem should probably be resolved by making Eclipse remember all notifications for a given test, not only the last one. Having "parallel exceptions", where the exception from the finally does not swallow the one from the try, would solve this issue too.
If you think about it, the situation you've described has Exception("First") as the root cause of Exception("second"), conceptually. The most useful thing for the user would probably be to get a stack dump showing a chain in that order...
In managed platforms, I can think of situations where it might be useful to have a disposer "elevate" an exception to something which is stronger, but not totally fatal to an application. For example, a "command" object's disposer might attempt to unwind the state of its associated connection to cancel any partially-performed commands. If that works, the underlying code may attempt to do other things with the connection. If the attempted "cancel" doesn't work, the exception should probably propagate out to the level where the connection would have been destroyed. In such a case, it may be useful for the exception to contain an "inner exception", though the only way I know to achieve that would be to have the attempted unwinding in a catch block rather than a "finally" block.

Is returning null after exception is caught bad design [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I always come across the same problem that when an exception is caught in a function that has a non-void return value I don't know what to return. The following code snippet illustrates my problem.
public Object getObject(){
try{
...
return object;
}
catch(Exception e){
//I have to return something here but what??
return null; // is this a bad design??
}
}
So my questions are:
Is return null bad design?
If so what is seen as a cleaner solution??
thanks.
I would say don't catch the exception if you really can't handle it. And logging isn't considered handling an error. Better to bubble it up to someone who can by throwing the exception.
If you must return a value, and null is the only sensible thing, there's nothing wrong with that. Just document it and make it clear to users what ought to be done. Have a unit test that shows the exception being thrown so developers coming after you can see what the accepted idiom needs to be. It'll also test to make sure that your code throws the exception when it should.
I always come across the same problem that when an exception is caught in a function that has a non-void return value I don't know what to return.
If you don't know what to return, then it means that you don't know how to handle the exception. In that case, re-throw it. Please, don't swallow it silently. And please, don't return null, you don't want to force the caller of the code to write:
Foo foo = bar.getFoo();
if (foo != null) {
// do something with foo
}
This is IMHO a bad design, I personally hate having to write null-checks (many times, null is used where an exception should be thrown instead).
So, as I said, add a throws clause to the method and either totally remote the try/catch block or keep the try/catch if it makes sense (for example if you need to deal with several exceptions) and rethrow the exception as is or wrap it in a custom exception.
Related questions
How to avoid “!= null” statements in Java?
Above all I prefer not to return null. That's something that the user has to explicitly remember to handle as a special case (unless they're expecting a null - is this documented). If they're lucky they'll deference it immediately and suffer an error. If they're unlucky they'll stick it in a collection and suffer the same problem later on.
I think you have two options:
throw an exception. This way the client has to handle it in some fashion (and for this reason I either document it and/or make it checked). Downsides are that exceptions are slow and shouldn't be used for control flow, so I use this for exceptional circumstances (pun intended)
You could make use of the NullObject pattern.
I follow a coding style in which I rarely return a null. If/when I do, that's explicitly documented so clients can cater for it.
Exceptions denote exceptional cases. Assuming your code was supposed to return an object, something must have gone wrong on the way (network error, out of memory, who knows?) and therefore you should not just hush it by returning null.
However, in many cases, you can see in documentation that a method returns a null when such and such condition occurs. The client of that class can then count on this behaviour and handle a null returned, nothing bad about that. See, in this second usage example, it is not an exceptional case - the class is designed to return null under certain conditions - and therefore it's perfectly fine to do so (but do document this intended behaviour).
Thus, at the end of the day, it really depends on whether you can't return the object because of something exceptional in your way, or you simply have no object to return, and it's absolutely fine.
I like the responses that suggest to throw an exception, but that implies that you have designed exception handling into the architecture of your software.
Error handling typically has 3 parts: detection, reporting, and recovery. In my experience, errors fall into classes of severity (the following is an abbreviated list):
Log for debug only
Pause whatever is going on and report to user, waiting for response to continue.
Give up and terminate the program with an apologetic dialogue box.
Your errors should be classified and handling should be as generically and consistently as possible. If you have to consider how to handle each error each time you write some new code, you do not have an effective error handling strategy for your software. I like to have a reporting function which initiates user interaction should continuation be dependent on a user's choice.
The answer as to whether to return a null (a well-worn pattern if I ever saw one) then is dependent on what function logs the error, what can/must the caller do if the function fails and returns the null, and whether or not the severity of the error dictates additional handling.
Exceptions should always be caught by the controller in the end.
Passing a <null> up to the controller makes no sense.
Better to throw/return the original exception up the stack.
It's your code and it's not bad solution. But if you share your code you Shoudn't use it because it can throw unexpected exception (as nullpointer one).
You can of course use
public Object getObject() throws Exception {}
which can give to parent function usable information and will warn that something bad can happen.
Basically I would ditto on Duffymo, with a slight addition:
As he says, if your caller can't handle the exception and recover, then don't catch the exception. Let a higher level function catch it.
If the caller needs to do something but should then appropriately die itself, just rethrow the exception. Like:
SomeObject doStuff()
throws PanicAbortException
{
try
{
int x=functionThatMightThrowException();
... whatever ...
return y;
}
catch (PanicAbortException panic)
{
cleanUpMess();
throw panic; // <-- rethrow the exception
}
}
You might also repackage the exception, like ...
catch (PanicAbortException panic)
{
throw new MoreGenericException("In function xyz: "+panic.getMessage());
}
This is why so much java code is bloated with if (x!=null) {...} clauses. Don't create your own Null Pointer Exceptions.
I would say it is a bad practice. If null is received how do I know if the object is not there or some error happened?
My suggestion is
never ever return NULL if the written type is an array or
Collection. Instead, return an empty Collection or an empty array.
When the return type is an object, it is up to you to return null depending on the scenario. But never ever swallow an exception and return NULL.
Also if you are returning NULL in any scenario, ensure that this is documented in the method.
As Josha Blooch says in the book "Effective Java", the null is a keyword of Java.
This word identifies a memory location without pointer to any other memory location: In my opinion it's better to coding with the separation of behavior about the functional domain (example: you wait for an object of kind A but you receive an object of kind B) and behavior of low-level domain (example: the unavailability of memory).
In your example, I would modify code as :
public Object getObject(){
Object objectReturned=new Object();
try{
/**business logic*/
}
catch(Exception e){
//logging and eventual logic leaving the current ojbect (this) in a consistent state
}
return objectReturned;
}
The disadvantage is to create a complete Object in every call of getObject() (then in situation where the object returned is not read or write).
But I prefer to have same object useless than a NullPointerException because sometimes this exception is very hard to fix.
Some thoughts on how to handle Exceptions
Whether returning null would be good or bad design depends on the Exception and where this snippet is placed in your system.
If the Exception is a NullPointerException you probably apply the catch block somewhat obtrusive (as flow control).
If it is something like IOException and you can't do anything against the reason, you should throw the Exception to the controller.
If the controller is a facade of a component he, translate the Exception to well documented component-specific set of possible Exceptions, that may occur at the interface. And for detailed information you should include the original Exception as nested Exception.

Throwing exceptions in Java

I have a question about throwing exceptions in Java, a kind of misunderstanding from my side, as it seems, which I would like to clarify for myself.
I have been reading that the two basic ways of handling exception code are:
1.) throwing an exception in a try-block with "throw new ...", and catching it immediately in a catch-block - the so called try-throw-catch mechanism.
2.) throwing an exception in a method with "throw new ..." and then declaring in the header of the method that this method might throw an exception with "throws ..." - the so called pass-the-buck.
I have recently read that "it doesn't make any sense to throw an exception and then catch it in the same method", which made me think whether I understand the thing in the wrong way, or the person who had written this had something else in mind. Doesn't the first way of handling exceptions does exactly this (the try-throw-catch mechanism) ? I mean, it throws an exception and catches it in the same method. I have read that it is a better practice to throw an exception in one method, and catch it in another method, but this is just one (probably better) way. The other way is also legal and correct, isn't it?
Would you, please, give me a comment on this ? Thank you very much.
Exceptions should be thrown from a method when that method is incapable of resolving the exception on its own.
For example, a FileNotFoundException is thrown from new FileInputStream(new File(filename)) because the FileInputStream itself can't handle a case where a file is missing; that exception needs to get thrown so the end-user application can handle the problem.
There are some cases where exceptions could be handled within a method. For example, a Document model method throwing a BadLocationException could be handled within a sufficiently intelligent method. Depending on the problem, either the exception can be handled or re-thrown.
(Anyway, I'd argue that throwing an exception from within a try-catch block so the catch block can be executed represents really bad logic flow)
I think you misunderstood the first case. Normally you add a try-catch-block when you call some method which may throw exceptions. Catching locally thrown exceptions indeed doesn't make much sense. In particular you shouldn't use exceptions to exit from loops, as this is extremely slow compared to a standard approach.
Doesn't the first way of handling
exceptions does exactly this (the
try-throw-catch mechanism)? I mean, it
throws an exception and catches it in
the same method.
That's not a "way of handling exceptions" - it's utter nonsense. The whole point of exceptions is to let another method up the call stack handle it. If you're going to handle the condition within the same method, there's no point in using an exception - that's what if() is for! If that makes the control flow of your method too complicated, you should probably refactor some of the logic into separate methods - and then it might make sense to have those throw exception that the remaining method body catches.
That being said, I can imagine one special case where it could make sense to throw and catch an exception in the same method: when you're already calling a method that may throw an exception and have a catch block to handle it, then in some cases it could make sense to throw an exception to indicate a similar problem that the existing catch block can handle in the same way.
The person who wrote "it doesn't make any sense to throw an exception and then catch it in the same method" is entitled to their opinion, but it's not widely shared. There are plenty of cases where throwing and catching an exception in the same method is what's needed. The simplest is where you are doing a sequence of operations and the failure of any one of them makes the rest invalid. If you detect that one of these operations fails it's perfectly reasonable to throw an exception and catch it at the end of the method. In fact it's the logical way of doing things. Arguably you could rewrite the code to not use the exception, maybe with some status flags and a break statement or two, but why would you? Using an exception makes it clear what's going on and improves code readability.
I'm gonna answer your questions in turn, then add some comments to the end. I'm not an authority on exception handling, but I hope my comments are helpful.
"Doesn't the first way of handling exceptions does exactly this"?
My answer is yes, as you describe it the first method does operate by throwing and catching an exception in the same method. However, I don't know that try-throw-catch has to work as you describe it.
"I have read that it is a better practice to throw an exception in one method, and catch it in another method, but this is just one (probably better) way. The other way is also legal and correct, isn't it?"
I agree that catching exceptions from a second method is better, but the first way is legal. Is it correct? well that's for you to decide, it is your code, after all.
For the most part, I agree that it doesn't make sense to throw an exception then immediately catch that exception in the same method. If we do this because the method is particularly long/complex and handling the error using other logic would complicate things more, then I would suggest moving some of this logic to another method and calling that method and catching its exception.
If our code is simpler, then it may be easy to handle the error using code that doesn't consist of throwing an exception.
My comments:
The try-throw-catch mechanism you mentioned may not need the exception to be thrown in the same method. I would have to read the text you found to be certain, but I would expect that it isn't necessary. If it didn't need the exception to be thrown in the same method, then your exceptions handling strategy is a combination of 1) and 2).
In the combo, one method would use try-throw-catch mechanism to catch an exception thrown by a called method. It seems to me that 1) and 2) should work together to form your exception handling strategy.
Now, maybe someone will come along and give us some wonderful reasons why we might want to throw an exception in the same method. I expect there are some, but to me they seem the exceptions, not the rule.
Cheers,
Ed
With the first way do you mean something like this:
try {
ok = doSomething();
if (!ok) {
throw new Exception("Error");
}
ok = doSomethingElse();
}catch (Exception e) {
}
This will allow you to exit the try-catch block without executing the rest of it. This is the only valid usage I can think of throwing an exception with throw and catching it yourself in a try-catch block. However, standard if blocks should be used instead. I don't understand why someone should throw an exception and then catch it himself.
The second way is more standard, especially if the caller of the method that throws an exception is an external module. This is a way of signaling that something real wrong happened. It is the responsibility of the caller to handle the exception.
If you're going to manually throw an exception, then obviously you know there has been some error that needs to be handled. Rather than throw the new exception, then catch it, then immediately handle the error, why not just handle the error? You (and the processor) don't need to go through all the work of generating an exception and catching it. The exception also makes the code harder to read and debug.
You would throw an exception, rather than just handling the error immediately, if:
Other code, like the code that called your method, should handle the error. For example, if your code is not UI code, then it probably shouldn't generate windows. This is your method #2.
You can take advantage of the try, catch, finally block. It's possible that you could write cleaner code this way, but I think that 90% of the time your code would be more readable using simple if statements.
My expierence is that using the first method gets your code quickly unreadable - since the functionality and the error-handling is getting mixed up. BUT it makes sense in some cases where you have a try{}catch{}finaly{} - for example in file handling or database handling where you ALLWAYS want the connection to be closed.
try{ //do something
}catch(Exception ex){
//log
}finally{
//connection.close
}
For everything else I use the second option - just for the reason to centralize my error-handling routines and keep the readability of the code implementing the businesslogic itself.
In my opinion, try blocks that you write should not include any "throw new" that are caught inside the same method. When you throw an exception, you're saying "I've encountered a situation that I can't handle; somebody else will have to deal with it." Your method with the "throw new" should either create an unchecked exception to throw or declare a checked exception in its method signature.
If you're using 3rd party classes that may throw exceptions, your method should have a try/catch block if you can actually handle the situation if an exception arises. Otherwise, you should defer to another class that can.
I don't create my own exception and then catch it in the same method.
Using an exception for control flow is specifically dealt with in Effective Java, 2nd Edition by Joshua Bloch, Item 57:
Item 57: Use exceptions only for exceptional conditions
...exceptions are, as their name implies, to be used only for exceptional conditions; they should never be used for ordinary control flow. [italics mine]
So while it certainly "works" to use exceptions to control flow, it is not recommended.
The reason why that would seem as nonsense ( throwing and catching in the same method ) is because that would be an scenario of using exceptions for flow control. If you already have enough data as to identify the condition where the exception should be thrown then you could use that information to use a condition instead.
See below:
1) Throwing and catching exception in same method ( wrong )
public void method() {
try {
workA...
workA...
workA...
workA...
if( conditionIvalid() && notEnoughWhatever() && isWrongMoment() ) {
throw new IllegalStateException("No the rigth time" );
}
workB...
workB...
workB...
workB...
} catch( IllegalStateException iee ) {
System.out.println( "Skiped workB...");
}
workC....
workC....
workC....
workC....
}
In this scenario the exception throwing are used to skip the section "workB".
This would be better done like this:
2) Using condition to control flow ( right )
public void method() {
workA...
workA...
workA...
workA...
if( !(conditionIvalid() && notEnoughWhatever() && isWrongMoment() ) ) {
//throw new IllegalStateException("No the rigth time" );
workB...
workB...
workB...
workB...
}
workC....
workC....
workC....
workC....
}
And then you can refactor the condition:
if( !(conditionIvalid() && notEnoughWhatever() && isWrongMoment() ) ) {
for
if( canProceedWithWorkB() ) {
implemented as:
boolean canProceedWithWorkB() {
return !(conditionIvalid() && notEnoughWhatever() && isWrongMoment() );
}

Categories