markdb314 markdb314 - 7 months ago 42
Swift Question

Simplest way to throw an error/exception with a custom message in Swift 2?

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 one case that has a String attached to it:

enum MyError : ErrorType {
    case RuntimeError(String)

Usage would be something like:

func throwError(message: String) throws {
    throw MyError.RuntimeError(message)
do {
    try throwError("foo")
} catch MyError.RuntimeError(let errorMessage) {

If you wish to use existing 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.