Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

swift

I want to do something in Swift 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. Ideas?

like image 222
markdb314 Avatar asked Oct 11 '22 04:10

markdb314


People also ask

How can a function throw an error in Swift?

Sometimes functions fail because they have bad input, or because something went wrong internally. Swift lets us throw errors from functions by marking them as throws before their return type, then using the throw keyword when something goes wrong.

How would you call a function that throws error and also returns a value in Swift?

It's called rethrows . The rethrows keyword is used for functions that don't directly throw an error.


2 Answers

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.

like image 150
Arkku Avatar answered Oct 14 '22 15:10

Arkku


The simplest way is to make String conform to Error:

extension String: Error {}

Then you can just throw a string:

throw "Some Error"

To make the string itself be the localizedString of the error you can instead extend LocalizedError:

extension String: LocalizedError {
    public var errorDescription: String? { return self }
}
like image 39
Nick Keets Avatar answered Oct 14 '22 17:10

Nick Keets