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.
Related
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.
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);
}
This is more of best practice question.
I'm working with old Java code at the moment. I'm seeing a lot of subclasses of Exception only overwrite the constructors. I'm not sure if there is any practical use of subclassing Exception like this. I think just calling the Exception constructor and pass in a message would be just as effective, and there wouldn't be many subclasses around. Code is liability.
The point of subclassing is that your code can distinguish different types of failure and treat them differently. If you just change the message, then a human can distinguish them in the logs, but that's all.
If the exceptions you are seeing are not actually handled differently, but just caught in a catch-all catch(Exception e) then perhaps someone was being over-enthusiastic with the subclasses, but it is often useful for cleanly separating layers of code and working out which classes should handle which kinds of problem.
For example, one type of exception may indicate a timeout, and it may be appropriate to retry after a short delay, whereas another type of exception indicates an unrecoverable failure (an invalid query, perhaps) which must be thrown up to a higher level or perhaps indicated to the user.
To add to the other answers:
If you extend Exception and throw it, you're declaring a new checked exception. It will have to be declared on the throws clause of your method. You are saying to the caller: "Here is a unusual case which you must code for".
I think checked exceptions are over-used. They are only really useful in situations where the caller can expect to recover from the problem. The vast majority of exceptions I have seen are the kind that the caller cannot reasonably expect to recover from. In this case you should use a RuntimeException descendant such as IllegalStateException or IllegalArgumentException and let top-level error handling take care of it.
This is done to allow more cleaner and more precise catching of exceptions. If all of your code just throws Exception, your exception-handling code will have to look like this:
try {
// ...
throw new Exception("configuration error");
// ...
throw new Exception("missing value error");
// etc.
} catch (Exception e) {
// do something
}
And it will be awkward at the least to handle different kinds of errors in different ways. More importantly, this code will swallow all exceptions, even ones you weren't expecting and for which you haven't written specific error-handling logic. On the other hand, if you write
try {
// ...
throw new ConfigurationException();
// ...
throw new MissingValueException();
// etc.
} catch (ConfigurationException e) {
System.err.println("error: bad configuration");
System.exit(1);
} catch (MissingValueException e) {
return DEFAULT_VALUE;
}
you'll be able to easily and cleanly handle different kinds of errors, and won't have to worry that your error handling code will be run in situations that you didn't expect it to.
When you have a subclass, you can catch it. You can't catch an exception selectively depending on its message.
Subclasses are more descriptive and easier to use:
throw new Exception("User does not exist " + userName);
compared to:
throw new UserNotExistsException(userName);
also the latter exception can have getUserName() method and field accordingly to extract important information when caught. You don't want to parse exception message, don't you?
Subclassing is the way to go. later in the lifetime of the application you may have to change the exception message. Who knows it may be displayed on a page and the wording needs to be adjusted.
Wrapping the error message in its own Exception subclass helps maintain a clean code and easily test against a given error category.
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.
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() );
}