我的假设是,只要程序正在运行,finally块就会被执行.但是,在此控制台应用程序中,finally块似乎没有被执行.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
try
{
throw new Exception();
}
finally
{
Console.WriteLine("finally");
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
产量

注意:当抛出异常时,Windows询问我是否要结束应用,我说'是'.
我发现了一个没有调用finally块的情况.
要点:
using System;
using System.Collections.Generic;
using System.Threading;
using System.ComponentModel;
class MainClass{
static IEnumerable<int> SomeYieldingMethod(){
try{
yield return 1;
yield return 2;
yield return 3;
}finally{
Console.WriteLine("Finally block!");
}
}
static void Main(){
Example(7);
Example(2);
Example(3);
Example(4);
}
static void Example(int iterations){
Console.WriteLine("\n Example with {0} iterations.", iterations);
var e = SomeYieldingMethod().GetEnumerator();
for (int i = 0; i< iterations; ++i) {
Console.WriteLine(e.Current);
e.MoveNext();
}
}
}
Run Code Online (Sandbox Code Playgroud)
结果如下:
Example with 7 iterations.
0
1
2
3
Finally block!
3
3
3 …Run Code Online (Sandbox Code Playgroud) 空try值具有某些价值,如其他地方所述
try{}
finally
{
..some code here
}
Run Code Online (Sandbox Code Playgroud)
但是,最后有什么用为空:
try
{
...some code here
}
finally
{}
Run Code Online (Sandbox Code Playgroud)
编辑:注意我还没有实际检查以查看CLR是否为空生成任何代码 finally{}
假设我要编写一个捕获KeyboardInterrupt异常的Python脚本,以便用户能够安全地使用Ctrl+ 终止C
但是,我无法将所有关键操作(如文件写入)放入catch块中,因为它依赖于局部变量并确保后续Ctrl+ C无论如何都不会破坏它.
使用带有empty(pass)try部分的try-catch块以及部件中的所有代码finally将这个片段定义为"原子,中断安全代码"并且可能不会在中途中断时,它是否有效并且是一种好习惯?
例:
try:
with open("file.txt", "w") as f:
for i in range(1000000):
# imagine something useful that takes very long instead
data = str(data ** (data ** data))
try:
pass
finally:
# ensure that this code is not interrupted to prevent file corruption:
f.write(data)
except KeyboardInterrupt:
print("User aborted, data created so far saved in file.txt")
exit(0)
Run Code Online (Sandbox Code Playgroud)
在这个例子中,我不关心当前生成的数据字符串,即可以中断创建并且不会触发写入.但是一旦写入开始,就必须完成,这就是我想要确保的.此外,如果在finally子句中执行写入时发生异常(或KeyboardInterrupt)会发生什么?
python try-catch try-catch-finally keyboardinterrupt try-finally
如果我有一个如下的协程,那么finally块中的代码会被调用吗?
public IEnumerator MyCoroutine(int input)
{
try
{
if(input > 10)
{
Console.WriteLine("Can't count that high.");
yield break;
}
Console.WriteLine("Counting:");
for(int i = 0; i < input; i++)
{
Console.WriteLine(i.ToString());
yield return null;
}
}
finally
{
Console.WriteLine("Finally!");
}
}
Run Code Online (Sandbox Code Playgroud) 这个很棒的代码,显示龙卷风gen模块中的内存泄漏,当连接关闭而不读取响应时:
import gc
from tornado import web, ioloop, gen
class MainHandler(web.RequestHandler):
@web.asynchronous
@gen.engine
def get(self):
gc.collect()
print len(gc.garbage) # print zombie objects count
self.a = '*' * 500000000 # ~500MB data
CHUNK_COUNT = 100
try:
for i in xrange(CHUNK_COUNT):
self.write('*' * 10000) # write ~10KB of data
yield gen.Task(self.flush) # wait for reciever to recieve
print 'finished'
finally:
print 'finally'
application = web.Application([
(r"/", MainHandler),
])
application.listen(8888)
ioloop.IOLoop.instance().start()Run Code Online (Sandbox Code Playgroud)
现在,多次运行一个简单的测试客户端
#!/usr/bin/python
import urllib
urlopen('http://127.0.0.1:8888/') # exit without reading response …Run Code Online (Sandbox Code Playgroud) 我有一个java程序,运行无限次.
程序代码:
void asd()
{
try
{
//inside try block
System.out.println("Inside try !!!");
asd();
}
finally
{
//inside finally
System.out.println("Inside finally !!!");
asd();
}
}
Run Code Online (Sandbox Code Playgroud)
输出:通过不断打印两个系统,该程序无限运行.
我的问题:在某些时候,它开始从try块中抛出StackOverflowErrors,因此它到达finally块,我们再次以递归方式调用此函数.但是,当我们已经面临StackOverflowError时,finally块中的递归函数如何执行?
JVM如何处理这种情况?如果我们也得到OutOfMemoryErrors会发生同样的行为吗?
在Java中,不建议finally在try-chatch块的section中抛出异常,因为它会隐藏任何throwable在tryor catch块中抛出的未处理的传播。blocker根据默认的声纳配置文件,此做法违反了液位。
声纳错误:从此finally块中删除此throw语句。
请考虑以下代码段。
例如:在finally块内关闭输入流,并在关闭流时处理可能的异常。
public void upload(File file) {
ChannelSftp c = (ChannelSftp) channel;
BufferedInputStream bis = new BufferedInputStream(file.toInputStream());
try {
String uploadLocation = Files.simplifyPath(this.fileLocation + "/" + file.getName());
c.put(bis, uploadLocation);
} catch (SftpException e) {
throw new IllegalTargetException("Error occurred while uploading " + e.getMessage());
} finally {
try {
bis.close();
} catch (IOException e) {
throw new UnsupportedOperationException("Exception occurred while closing Input stream " + e.getMessage());
} …Run Code Online (Sandbox Code Playgroud) 在 Python 程序中,我的代码具有以下结构:
try:
value = my_function(*args)
finally:
with some_context_manager:
do_something()
if 'value' in locals():
do_something_else(value)
Run Code Online (Sandbox Code Playgroud)
但是'value' in locals()结构感觉有点脆弱,我想知道是否有更好的方法来做到这一点。
我真正想要的是finally根据try块是否引发异常,内部代码的行为略有不同。有没有办法知道是否引发了异常?
我正在使用尝试/最后在Powershell中编写监视脚本,以在脚本结束时记录消息。该脚本旨在无限期运行,因此我想要一种跟踪意外退出的方法。
我检查过的所有其他StackOverflow发布和帮助页面都指出:
即使您使用CTRL + C来停止脚本,Final块也会运行。如果Exit关键字从Catch块中停止脚本,则Final块也将运行。
实际上,我还没有发现这是真的。我正在使用以下人为设计的示例进行测试:
Try {
While($True) {
echo "looping"
Start-Sleep 3
}
} Finally {
echo "goodbye!"
pause
}
Run Code Online (Sandbox Code Playgroud)
无论是作为保存的脚本运行还是通过内置Powershell ISE执行时,Finally每次在Ctrl+ C(无回声,无暂停)之后都将跳过此处的块。我得到的唯一输出是:
looping
looping
...(repeat until Ctrl-C)
Run Code Online (Sandbox Code Playgroud)
我显然错过了一些东西,但是我不知道它是什么,尤其是在这么小的代码片段中。
try-finally ×10
c# ×4
python ×3
try-catch ×3
exception ×2
java ×2
yield ×2
.net ×1
coroutine ×1
generator ×1
ienumerator ×1
jvm ×1
memory-leaks ×1
powershell ×1
recursion ×1
sonarqube ×1
tornado ×1