如何在PowerShell中使用'throw'方向来抛出自定义数据对象的异常?说,它能做到吗?:
throw 'foo', $myData
Run Code Online (Sandbox Code Playgroud)
那么数据可以用在'catch'逻辑中:
catch {
if ($_.exception.some_property -eq 'foo') {
$data = $_.exception.some_field_to_get_data
# dealing with data
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:
我的目的是知道是否有一个简短而酷的语法来抛出异常(没有显式创建我自己的类型),其名称我可以通过其名称来决定并在'catch'块中处理它的数据.
我曾经认为,如果goroutine中的恐慌的调用者在恐慌之前完成,它将使其终止程序(延迟恢复没有任何帮助,因为此时还没有发生恐慌),
直到我尝试以下代码:
func fun1() {
fmt.Println("fun1 started")
defer func() {
if err := recover(); err != nil {
fmt.Println("recover in func1")
}
}()
go fun2()
time.Sleep(10 * time.Second) // wait for the boom!
fmt.Println("fun1 ended")
}
func fun2() {
fmt.Println("fun2 started")
time.Sleep(5 * time.Second)
panic("fun2 booom!")
fmt.Println("fun2 ended")
}
Run Code Online (Sandbox Code Playgroud)
我发现无论调用者函数完成与否,如果goroutines开始出现恐慌,调用者的延迟恢复机制都将无济于事。整个程序仍然无效。
所以为什么?理论上,调用者功能仍在运行。当出现紧急情况时,调用者的延迟功能应起作用(包括恢复)。