斯威夫特可以捕获致命错误? [英] swift can catch fatal error?

查看:185
本文介绍了斯威夫特可以捕获致命错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Swift 2.0 try-catch。

I am trying to use Swift 2.0 try-catch.

我原来有以下代码

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

但它会产生错误

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

    return open;
}

因此我将viewDidLoad()中的代码更改为:

Therefore I changed the code in viewDidLoad() to:

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

但它不起作用!!!

我猜swift的try-catch与C,C#不同。

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;
    }
}


推荐答案

你不应该抓住fatalerror。它表示编程错误。您没有发现编程错误,修复了代码。崩溃是故意的,你故意不能阻止它。

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.

Swift 2中提供了涉及关键字try,catch和throw的内容,但这与您似乎正在考虑的C ++异常完全不同。

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.

这篇关于斯威夫特可以捕获致命错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆