try-finally is a clause used to define a block of code which may throw an exception along with instructions to execute regardless of whether an exception occurs or not.
I am not sure why we need finally in try...except...finally statements. In my opinion, this code block
try:
run_code1()
except TypeError:
run_code2()
other_code()
is the same with this one using finally:
try:
run_code1()
except…
Take a look at the following two methods:
public static void foo() {
try {
foo();
} finally {
foo();
}
}
public static void bar() {
bar();
}
Running bar() clearly results in a StackOverflowError, but running foo()…
How does a return statement inside a try/catch block work?
function example() {
try {
return true;
}
finally {
return false;
}
}
I'm expecting the output of this function to be true, but instead it is false!
I have a simple Java class as shown below:
public class Test {
private String s;
public String foo() {
try {
s = "dev";
return s;
}
finally {
s = "override variable s";
…
I'm reviewing some new code. The program has a try and a finally block only. Since the catch block is excluded, how does the try block work if it encounters an exception or anything throwable? Does it just go directly to the finally block?
What's the difference between
try {
fooBar();
} finally {
barFoo();
}
and
try {
fooBar();
} catch(Throwable throwable) {
barFoo(throwable); // Does something with throwable, logs it, or handles it.
}
I like the second version better…
We've seen plenty of questions about when and why to use try/catch and try/catch/finally. And I know there's definitely a use case for try/finally (especially since it is the way the using statement is implemented).
We've also seen questions about…
Is it possible to tell if there was an exception once you're in the finally clause? Something like:
try:
funky code
finally:
if ???:
print('the funky code raised')
I'm looking to make something like this more DRY:
try:
funky…
With the following code:
try {
throw new RuntimeException ("main");
}
finally {
throw new RuntimeException ("finally");
}
I get this result:
Exception in thread "main" java.lang.RuntimeException: finally
at…
Will the following code:
while True:
try:
print("waiting for 10 seconds...")
continue
print("never show this")
finally:
time.sleep(10)
Always print the message "waiting for 10 seconds...", sleep for 10…
Take the following code as a sample:
procedure TForm1.Button1Click(Sender: TObject);
var
Obj: TSomeObject;
begin
Screen.Cursor:= crHourGlass;
Obj:= TSomeObject.Create;
try
// do something
finally
Obj.Free;
end;
…
When compiling the following code with a simple try/finally block, the Java Compiler produces the output below (viewed in the ASM Bytecode Viewer):
Code:
try
{
System.out.println("Attempting to divide by zero...");
System.out.println(1 /…