Reputation: 1941
I have a question regarding try/catch and exceptions in Java. I know this should be basic knowledge, but I think I miss a part of the understand of how this works. Given this code for example:
String res = "";
try {
res = methodThatCanThrowException();
res = res + ".txt";
} catch (Exception e) {
res = "somethingwentwrong.txt";
}
return res;
Am I guaranteed that 'res' will never be set both in the try AND the catch block? If an exception is thrown inside the methodcall in the try block, the code control goes directly to the catch block, right? Is there any scenarios where 'res' will be given a value both in the try and the catch block?
Upvotes: 4
Views: 6581
Reputation: 4979
When an exception occurs inside a try block, control goes directly to the catch block, so no other code will be executed inside the try block and the value of res will not change. Also when a method throws an exception it does not return anything. So in case of an exception, res will only be set once when it is initialised outside the try catch block, and then later when inside the catch block.
Never more than twice
Upvotes: 0
Reputation: 96016
The best answer you can get is from the JLS - 14.20.1. Execution of try-catch:
A
try
statement without afinally
block is executed by first executing thetry
block. Then there is a choice:...
If the run-time type of
V
is assignment compatible with (§5.2) a catchable exception class of any catch clause of thetry
statement, then the first (leftmost) suchcatch
clause is selected. The valueV
is assigned to the parameter of the selectedcatch
clause, and the Block of that catch clause is executed...
I don't want to paste the whole section because it's big, I highly advise you to go through it to better understand the mechanism of try-catch-finally.
Upvotes: 2
Reputation: 394146
If methodThatCanThrowException
throws an exception, res
won't get assigned in the try
block, so only the catch
block would assign it (assuming you fix your catch block).
However, even if the exception was thrown after res
is already assigned, the catch block would overwrite it with a new value, so it doesn't matter if it is assigned by both.
Upvotes: 2
Reputation: 52205
If no exception takes place within the try
block, the catch
block will never be executed.
If, on the other hand, an exception does take place, control flow moves from the try
block to your catch
block, and the res
variable would be overwritten with whatever it is you have in the catch
block.
In your case, res
will be have either whatever methodTatCanThrowException()
returns with .txt
appended to it or somethingwentwrong.txt
.
As a side note, you might also want to look into the finally
block and what it does.
Upvotes: 0
Reputation: 989
You are right. If methodThatCanThrowException
throws an execption it will jump to res = "somethingwentwrong.txt";
. There is never a scenario with both lines excecuted
Upvotes: 0