在Swift 2中使用自定义消息引发错误/异常的最简单方法是? [英] Simplest way to throw an error/exception with a custom message in Swift 2?

查看:78
本文介绍了在Swift 2中使用自定义消息引发错误/异常的最简单方法是?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Swift 2中做一些我常用的其他多种语言的操作:抛出带有自定义消息的运行时异常.例如(在Java中):

throw new RuntimeException("A custom message here")

我知道我可以抛出符合ErrorType协议的枚举类型,但是我不想为我抛出的每种错误类型都定义枚举.理想情况下,我希望能够尽可能地模仿以上示例.我考虑创建一个实现ErrorType协议的自定义类,但是我什至无法弄清楚该协议需要什么(请参阅解决方案

最简单的方法可能是定义 one 自定义enum,其中只有一个case并且附加了String它:

enum MyError: ErrorType {
    case runtimeError(String)
}

或者,从Swift 4开始:

enum MyError: Error {
    case runtimeError(String)
}

示例用法如下:

func someFunction() throws {
    throw MyError.runtimeError("some message")
}
do {
    try someFunction()
} catch MyError.runtimeError(let errorMessage) {
    print(errorMessage)
}

如果您想使用现有的Error类型,最通用的类​​型是NSError,您可以使用工厂方法来创建并使用自定义消息来抛出.

I want to do something in Swift 2 that I'm used to doing in multiple other languages: throw a runtime exception with a custom message. For example (in Java):

throw new RuntimeException("A custom message here")

I understand that I can throw enum types that conform to the ErrorType protocol, but I don't want to have to define enums for every type of error I throw. Ideally, I'd like to be able mimic the example above as closely as possible. I looked into creating a custom class that implements the ErrorType protocol, but I can't even figure out that what that protocol requires (see documentation). Ideas?

解决方案

The simplest approach is probably to define one custom enum with just one case that has a String attached to it:

enum MyError: ErrorType {
    case runtimeError(String)
}

Or, as of Swift 4:

enum MyError: Error {
    case runtimeError(String)
}

Example usage would be something like:

func someFunction() throws {
    throw MyError.runtimeError("some message")
}
do {
    try someFunction()
} catch MyError.runtimeError(let errorMessage) {
    print(errorMessage)
}

If you wish to use existing Error types, the most general one would be an NSError, and you could make a factory method to create and throw one with a custom message.

这篇关于在Swift 2中使用自定义消息引发错误/异常的最简单方法是?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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