The easiest way to throw an error / exception using a special message in Swift 2?

I want to do something in Swift 2 that I'm used to doing in several other languages: throw an exception from the runtime using a special message. For example (in Java):

throw new RuntimeException("A custom message here") 

I understand that I can list enumeration types that correspond to the ErrorType protocol, but I do not want to define enumerations for each type of error that I throw. Ideally, I would like to imitate the above example as best as possible. I learned how to create a custom class that implements the ErrorType protocol, but I cannot even figure out what is required for this protocol (see documentation ). Ideas?

+106
ios swift swift2
Jul 16 '15 at 0:50
source share
9 answers

The simplest approach is probably to define one user enum with only one case which String attached:

 enum MyError: ErrorType { case runtimeError(String) } 

Or, as in Swift 4:

 enum MyError: Error { case runtimeError(String) } 

A usage example would be something like:

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

If you want to use existing Error types, the most common one is NSError , and you can create a factory method to create and throw it with a custom message.

+157
Jul 16 '15 at 0:58
source share

The easiest way: String match Error :

 extension String: Error {} 

Then you can just throw away the line:

 throw "Some Error" 

For the string itself to be localizedString errors, you can extend LocalizedError :

 extension String: LocalizedError { public var errorDescription: String? { return self } } 
+112
Nov 16 '16 at 10:12
source share

@ The nick-keets solution is most elegant, but for me for a test purpose it was broken with the following compile-time error:

Redundant conformance of 'String' to protocol 'Error'

Here's a different approach:

 struct RuntimeError: Error { let message: String init(_ message: String) { self.message = message } public var localizedDescription: String { return message } } 

And use:

 throw RuntimeError("Error message.") 
+15
Aug 23 '17 at 7:21
source share

Check out this cool version. The idea is to implement both the String and ErrorType protocols and use the rawValue error.

 enum UserValidationError: String, Error { case noFirstNameProvided = "Please insert your first name." case noLastNameProvided = "Please insert your last name." case noAgeProvided = "Please insert your age." case noEmailProvided = "Please insert your email." } 

Using:

 do { try User.define(firstName, lastName: lastName, age: age, email: email, gender: gender, location: location, phone: phone) } catch let error as User.UserValidationError { print(error.rawValue) return } 
+13
Aug 08 '16 at 17:13
source share

Swift 4:

According to:

https://developer.apple.com/documentation/foundation/nserror

if you don't want to define a custom exception, you can use the standard NSError object as follows:

 import Foundation do { throw NSError(domain: "my error description", code: 42, userInfo: ["ui1":12, "ui2":"val2"] ) } catch let error as NSError { print("Caught NSError: \(error.localizedDescription), \(error.domain), \(error.code)") let uis = error.userInfo print("\tUser info:") for (key,value) in uis { print("\t\tkey=\(key), value=\(value)") } } 

Print:

 Caught NSError: The operation could not be completed, my error description, 42 User info: key=ui1, value=12 key=ui2, value=val2 

This allows you to provide a custom string, as well as a numeric code and a dictionary with all the necessary additional data of any type.

Note: this has been tested on OS = Linux (Ubuntu 16.04 LTS).

+11
Oct 06 '17 at 16:40
source share

Based on @Nick keets answer, here is a more complete example:

 extension String: Error {}/*Enables you to throw a string*/ extension String: LocalizedError {/*Adds error.localizedDescription to Error instances*/ public var errorDescription: String? { return self } } func test(color:NSColor) throws{ if color == .red { throw "I don't like red" }else if color == .green { throw "I'm not into green" }else { throw "I like all other colors" } } do { try test(color:.green) } catch let error where error.localizedDescription == "I don't like red"{ Swift.print ("Error: \(error)")//"I don't like red" }catch let error { Swift.print ("Other cases: Error: \(error.localizedDescription)")/*I like all other colors*/ } 

Originally posted on my quick blog: http://eon.codes/blog/2017/09/01/throwing-simple-errors/

+3
Sep 01 '17 at 11:49 on
source share

The simplest solution without additional extensions, enumerations, classes, etc.:

 NSException(name:NSExceptionName(rawValue: "name"), reason:"reason", userInfo:nil).raise() 
+3
Apr 14 '18 at 12:43
source share

I like @ Alexander-Borisenko's answer, but the localized description was not returned when an error was detected. It seems that you need to use LocalizedError instead:

 struct RuntimeError: LocalizedError { let message: String init(_ message: String) { self.message = message } public var errorDescription: String? { return message } } 

See this answer for more details.

+2
Nov 28 '18 at 11:27
source share

Just use fatalError: fatalError ("Custom message here")

0
May 01, '19 at 21:25
source share



All Articles