当语言不支持析构函数时如何对堆栈展开做出反应?

发布于 2024-09-26 22:31:14 字数 230 浏览 4 评论 0原文

假设您已经创建了 Window 类的实例。该窗口显示给用户。然后,抛出异常,并且对实例的引用丢失,但用户仍然可以看到该窗口,因为该实例仍然存在(只是不再被引用)。

在这些情况下该怎么办?

我特别谈论的是 Squirrel 脚本语言 (http://www.squirrel-lang.org/)。与Java相反,它似乎没有finally块或终结器方法,那么这种语言的异常处理是否被破坏了?

Suppose you have created an instance of a Window class. The window is shown to the user. Then, an exception is thrown, and reference to the instance is lost, but the window is still seen by the user because the instance still exists (it's just not referenced anymore).

What to do in these circumstances?

I'm specifically talking about the Squirrel scripting language (http://www.squirrel-lang.org/). Contrary to Java, it doesn't seem to have finally blocks or finalizer methods, so is exception handling broken in this language?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

单身情人 2024-10-03 22:31:14

我不知道squirrel,但即使没有finally块,你也可以在Java中某种程度上模拟行为:

Exception error = null;
try {
 // do something
}
catch (Exception e) {
  error = e;
}
// My finally code goes here
// ...
if (error != null) {
  // Oh dear clean up all my resources - files, windows, sockets etc.
  throw error;
}

所以catch块将异常存储在一个变量中,如果你想重新抛出它,你可以稍后测试它,并且它仍然让您有机会进行其他清理工作。显然,您必须注意一些细微差别(例如,需要特殊处理的显式异常类型、在 try/catch 之外抛出更多异常),但经过仔细考虑,您应该没问题。

在 Java 和其他垃圾收集语言中,系统资源(如图形句柄、套接字、窗口、文件句柄等)往往有点混乱。通常这些资源将由具有显式 close() 方法的类进行管理。因此,如果您知道事物已落入堆中,您通常会在对象上调用显式 close() 来立即清理它们。否则,对象将在终结期间自行清理,但仅在 GC 期间进行清理,这可能需要很长时间。

I don't know squirrel, but even in the absence of a finally block you could simulate the behaviour to some extent within Java:

Exception error = null;
try {
 // do something
}
catch (Exception e) {
  error = e;
}
// My finally code goes here
// ...
if (error != null) {
  // Oh dear clean up all my resources - files, windows, sockets etc.
  throw error;
}

So the catch block stores the exception in a variable that you can test later if you want to rethrow it, and it still allows you the chance to do other cleanup. Obviously there are nuances that you have to be aware of (e.g. explicit kinds of exception that need special handling, more exceptions being thrown outside the try / catch) but with careful consideration you should be okay.

System resources (like graphics handles, sockets, windows, file handles etc.) in particular tend to be a bit messy in Java and other garbage collected languages. Usually these resources will be managed by a class with an explicit close() method. So if you know things have fallen in a heap you would normally invoke an explicit close() on the objects to clean them up straightaway. Otherwise the object will cleanup itself during finalization but only during GC which could be a long time coming.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文