Swift 中的 try-catch 异常 [英] try-catch exceptions in Swift

查看:40
本文介绍了Swift 中的 try-catch 异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 Swift 中捕获异常?给定以下代码:

Is it possible to catch exceptions in Swift? Given the following code:

NSException.raise(NSRangeException,
    format: "Now you've gone too far!",
    arguments: CVaListPointer(fromUnsafePointer: UnsafePointer()))

是否可以防止异常导致整个程序崩溃?也就是说,在 Objective-C 中,Swift 等价物是什么:

Is it possible to prevent the exception from crashing the entire program? That is, what is the Swift equivalent of the following in Objective-C:

@try {
    [NSException raise:NSRangeException format:@"Now you've gone too far!"];
}

推荐答案

它没有异常处理,开发者论坛中的这个讨论讨论了为什么会这样:

但请记住,Cocoa 和 Cocoa Touch 传统上并不打算为您捕捉异常;他们打算让你不要让他们首先被抛出.应处理普通错误可选类型和 inout NSError 参数;你应该解决任何导致断言失败的情况(这似乎是唯一的Swift 中的异常抛出机制)通过编写更好的代码.

but keep in mind that Cocoa and Cocoa Touch traditionally don't intend for you to catch exceptions; they intend for you to not cause them to be thrown in the first place. Ordinary errors should be handled with optional types and inout NSError parameters; you should address any situation that causes an assertion to fail (which seems to be the only exception-throwing mechanism in Swift) by writing better code.

这篇关于Swift 中的 try-catch 异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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