swift can catch fatal error?

核能气质少年 提交于 2019-11-26 22:04:23

问题


I am trying to use Swift 2.0 try-catch.

I originally had the following code

override func viewDidLoad()
{
    var obj : Object?;
    Hi( obj );
}

But it procdues an error

func Hi( open : Open? ) -> Open?
{
    open!.Hi(); <-- here is error point. Fatal error !
    print( "OK" );

    return open;
}

Therefore I changed the code in viewDidLoad() to:

override func viewDidLoad()
{
    try
    {
        var obj : Object?;
        Hi( obj );
    }
    catch
    {
        print( "bug !!!" ); <- I want to this !!!
    }
}

But it does not work !!!

I guess swift's try-catch is different than in C, C#.

How can I catch the fatal error ?

Might the following be a proper swift way?

func Hi( open : Open? ) -> Open?
{
    if let op = open
    {
        op.Hi();
        print( "OK" );

        return open;
    }
    else
    {
        return nil;
    }
}

回答1:


You are not supposed to catch fatalerror. It indicates a programming error. You don't catch programming errors, you fix your code. The crash is intentional and it is intentional that you cannot stop it.

Something involving the keywords try, catch and throw is available in Swift 2, but that is nothing like C++ exceptions that you seem to be thinking about.




回答2:


When you're calling Hi() like this: open!.Hi();, your program can crash if open is nil.

open is a parameter, and the value that is passed as that parameter is defined on the call site as such: var obj : Object?;. You're defining a new variable named obj with type Object?, but you're not assigning it a value. This means that obj will be nil and therefore open will be nil and this leads to open!.Hi() crashing.

To solve it, make sure to assign a value to the parameter of Hi. It might be better to make the parameter non-optional as well, so you don't have to force unwrap it to call a function on it.



来源:https://stackoverflow.com/questions/31335023/swift-can-catch-fatal-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!