在 Flash AS3 中,我想写单曲 尝试捕捉 阻止以捕获整个类(class)中的任何错误。
例如,我在 myClass.as 中有很多函数。我不想在每个函数中写入 try catch 块以捕获此函数中的错误。
有没有办法做到这一点?
谢谢!
最佳答案
你不能!除了AS3之外,即使在其他语言中也没有这样简单的方法,除非他们使用AOP方法来做到这一点。
最佳实践是让您的类冒泡错误(异常)并让更高层捕获并处理错误。
编辑 - 关于评论
其实这个想法是自然的方式..仍然需要手动捕获每个可能的错误。我给你举个例子。请注意,示例的目的只是为了清楚地区分较低层和较高层。
例如,您在中间层(您的业务流程)中有一个类:
public class MyBussiness {
public function loadImages(){
//for example here is a block of method
//possibly throws exception.
}
public function getLoan(){
//lets assume here too
}
}
在更高层(我假设在您的 View - MXML)中,您会捕获如下异常:
var myBussiness:MyBussiness = new MyBussiness():
try {
myBussiness.loadImages();
//any other sequence process
myBussiness.getLoan();
}
catch(error:Error){
//here you process error
//show it to user or make LOG
}
它仍然不能像您期望的那样神奇,但这是最佳实践。 记住只在可能抛出错误的代码上放置 try catch 因为 try catch 很贵。
关于actionscript-3 - 在 Flash AS3 中如何放置单个 try catch 代码,以捕获整个类中的任何错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3455577/