235

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?

1
  • 2
    Swift 2 throw/catch are not exceptions.
    – zaph
    Jul 16, 2015 at 12:26

14 Answers 14

279

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

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.

7
  • Hi, I know it's been a year you posted this answer, but I would like to know if it's possible to get the String inside your errorMessage, if so, how do I do that? May 12, 2017 at 1:40
  • 2
    @RenanCamaforte I'm sorry, I don't understand the question? The String is associated here with the MyError.RuntimeError (set at the time of throw), and you gain access to it at the catch (with let errorMessage).
    – Arkku
    May 12, 2017 at 8:01
  • 3
    You were asked for the simpliest solution. Solution when you create custom enums, functions and etc is not simple. I know at least one way but I won't post it there because it is for objective-C Apr 14, 2018 at 12:26
  • 6
    @VyachaslavGerchicov If you don’t know a simpler way for Swift, which was also specified in the question, then this would be the simplest way, even of you don’t consider it simple in a more general context that would include Objective-C. (Also, this answer is basically a one-line one-time definition of an enum, the function and its call is an example of usage, not part of the solution.)
    – Arkku
    Apr 14, 2018 at 12:31
  • 3
    @Otar Yes, but… you are talking about try!, which isn't used here. You indeed can't even make the potentially throwing call without some kind of try. (Also that part of the code is the example usage, not the actual solution.)
    – Arkku
    Jan 23, 2019 at 21:10
204

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 }
}
7
  • This is clever, but is there a way to make its localizedDescription be the string itself?
    – villapossu
    Jan 25, 2017 at 10:56
  • 2
    Elegant indeed! But it breaks down for me in test targets with the following message Redundant conformance of 'String' to protocol 'Error' :( Aug 23, 2017 at 7:09
  • 2
    For some reason this doesn't work for me. Says it can't complete the operation when parsing error.localizedDescription after throwing a string.
    – Noah Allen
    Dec 11, 2018 at 20:51
  • 8
    Warning: this extension caused problems for me with external libraries. Here's my example. This is possible for any 3rd party library that manages Errors; I would avoid extensions that make String conform to Error. Jan 10, 2020 at 2:10
  • 18
    A protocol should declare what a type "is", not what it "might be". A string is not always an error, and this extension makes it easy to accidentally assume that it is, defeating type safety.
    – dbplunkett
    Aug 21, 2020 at 16:07
42

@nick-keets's solution is most elegant, but it did break down for me in test target with the following compile time error:

Redundant conformance of 'String' to protocol 'Error'

Here's another approach:

struct RuntimeError: LocalizedError {
    let description: String

    init(_ description: String) {
        self.description = description
    }

    var errorDescription: String? {
        description
    }
}

And to use:

throw RuntimeError("Error message.")

Important: Updated to use LocalizedError instead of Error. Using Error and overriding localizedDescription will NOT return a correct description. Instead, it will look like this: The operation couldn’t be completed. (__lldb_expr_39.RuntimeError error 1.)

41

Swift 4:

As per:

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

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

import Foundation

do {
  throw NSError(domain: "my error domain", 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)")
  }
}

Prints:

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

This allows you to provide a custom string (the error domain), plus a numeric code and a dictionary with all the additional data you need, of any type.

N.B.: this was tested on OS=Linux (Ubuntu 16.04 LTS).

5
  • 3
    It seems outside the API intent to pass "my error description" to a parameter called domain. Nov 23, 2020 at 12:57
  • 2
    The fix highlights a second problem: The catch block has error.localizedDescription, but that description doesn't get set to anything in the throw statement. So you end up with just a generic "The operation could not be completed" error. Nov 24, 2020 at 17:35
  • @EdwardBrey it was left for illustration purposes only, there are plenty other fields that the user can customize. Nov 25, 2020 at 11:28
  • 1
    Event with error.localizedDescription I get the domain and the code from NSError. In console I see a message that follows this pattern The operation couldn’t be completed. (\(domain) error \(code).). This looks good to me, thank you PJ for sharing this Jul 19, 2022 at 15:18
  • I added an answer that uses NSLocalizedDescriptionKey in the userInfo dictionary, which is the documented way to provide the message string.
    – bshirley
    Jan 28 at 18:19
21

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

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."
}

Usage:

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
}
2
  • There seems to be little benefit in this approach, as you still need the as User.UserValidationError and on top of that the .rawValue. However, if you instead implemented CustomStringConvertible as var description: String { return rawValue }, it might be useful to get the custom descriptions using the enum syntax without having to go through rawValue in every place where you print it.
    – Arkku
    Oct 18, 2018 at 11:49
  • 2
    better implement localizedDescription method to return .rawValue
    – DanSkeel
    Dec 12, 2018 at 17:41
17

Simplest solution without extra extensions, enums, classes and etc.:

NSException(name:NSExceptionName(rawValue: "name"), reason:"reason", userInfo:nil).raise()
3
  • 3
    re. your comments on my answer, this is simple only in the sense that you have somewhat arbitrarily decided that defining and enum or extension once is complicated. So, yes, your answer has zero lines of "setup", but at the cost of having every thrown exception be a complicated and non-Swiftlike (raise() instead of throw) spell that is hard to remember. Compare your solution with throw Foo.Bar("baz") or throw "foo" multiplied by the number of places where an exception is thrown – IMO the one-time fee of one-line extension or enum is far preferable to things like NSExceptionName.
    – Arkku
    Apr 14, 2018 at 13:01
  • @Arkku For example postNotification requires 2-3 params and its selector is similar to this one. Do you override Notification and/or NotificationCenter in each project to allow it to accept less input params? Apr 14, 2018 at 13:15
  • 2
    No, and I wouldn't even use the solution in my own answer; I only posted it to answer the question, not because it is something I would do myself. Anyway, that is besides the point: I stand by the opinion that your answer is by far more complicated to use than either mine or Nick Keets's. Of course there are other valid points to consider, such as if extending String to conform to Error is too surprising, or if a MyError enum is too vague (personally I would answer yes to both, and instead do a separate enum case for each error, i.e., throw ThisTypeOfError.thisParticularCase).
    – Arkku
    Apr 14, 2018 at 13:22
9

In case you don't need to catch the error and you want to immediately stop the application you can use a fatalError: fatalError ("Custom message here")

1
  • 8
    Note that this will not throw an error which can be caught. This will crash the app. Dec 31, 2019 at 15:28
7

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 published on my swift blog: http://eon.codes/blog/2017/09/01/throwing-simple-errors/

4
  • 2
    TBH: I now just do throw NSError(message: "err", code: 0)
    – Sentry.co
    Feb 24, 2020 at 15:12
  • 1
    So you don't even use your own example? :D Oh, and the first argument should be domain, not message, right?
    – NRitH
    Feb 25, 2020 at 21:31
  • 1
    Your right, domain. And no, adds too much sugar in the code. I usually make alot of small frameworks and modules and try to keep convenient extension sugar low. These days I try to use a mix between Result and NSError
    – Sentry.co
    Feb 27, 2020 at 9:47
  • 1
    catch let error where error.localizedDescription == "I don't like red" is brittle, this would be a good candidate for a strongly typed error enum. And another solution here showed potential issues when conforming String to Error globally.
    – stef
    Jul 24, 2021 at 19:38
4

First, let's see few usage examples, then how to make those samples work (Definition).

Usage

do {
    throw MyError.Failure
} catch {
    print(error.localizedDescription)
}

Or more specific style:

do {
    try somethingThatThrows()
} catch MyError.Failure {
    // Handle special case here.
} catch MyError.Rejected {
    // Another special case...
} catch {
    print(error.localizedDescription)
}

Also, categorization is possible:

do {
    // ...
} catch is MyOtherErrorEnum {
    // If you handle entire category equally.
} catch let error as MyError {
    // Or handle few cases equally (without string-compare).
    switch error {
    case .Failure:
        fallthrough;
    case .Rejected:
        myShowErrorDialog(error);
    default:
        break
    }
}

Definition

public enum MyError: String, LocalizedError {
    case Failure = "Connection fail - double check internet access."
    case Rejected = "Invalid credentials, try again."
    case Unknown = "Unexpected REST-API error."

    public var errorDescription: String? { self.rawValue }
}

Pros and Cons

Swift defines error variable automatically, and a handler only needs to read localizedDescription property.

But that is vague, and we should use "catch MyError.Failure {}" style instead (to be clear about what-case we handle), although, categorization is possible as shown in usage example.

  1. Teodor-Ciuraru's answer (which's almost equal) still needs a long manual cast (like "catch let error as User.UserValidationError { ... }").

  2. The accepted categorization-enum approach's disadvantages:

    • Is too vague as he comments himself, so that catchers may need to compare String message!? (just to know exact error).
    • For throwing same more than once, needs copy/pasting message!!
    • Also, needs a long phrase as well, like "catch MyError.runtimeError(let errorMessage) { ... }".
  3. The NSException approach has same disadvantages of categorization-enum approach (except maybe shorter catching paragraph), also, even if put in a factory method to create and throw, is quite complicated.

Conclusion

This completes other existing solutions, by simply using LocalizedError instead of Error, and hopefully saves someone from reading all other posts like me.

(My laziness sometimes causes me a lot of work.)

Testing

import Foundation
import XCTest
@testable import MyApp

class MyErrorTest: XCTestCase {
    func testErrorDescription_beSameAfterThrow() {
        let obj = MyError.Rejected;
        let msg = "Invalid credentials, try again."
        XCTAssertEqual(obj.rawValue, msg);
        XCTAssertEqual(obj.localizedDescription, msg);
        do {
            throw obj;
        } catch {
            XCTAssertEqual(error.localizedDescription, msg);
        }
    }

    func testThrow_triggersCorrectCatch() {
        // Specific.
        var caught = "None"
        do {
            throw MyError.Rejected;
        } catch MyError.Failure {
            caught = "Failure"
        } catch MyError.Rejected {
            caught = "Successful reject"
        } catch {
            caught = "Default"
        }
        XCTAssertEqual(caught, "Successful reject");
    }
}

Other tools:

#1 If implementing errorDescription for each enum is a pain, then implement it once for all, like:

extension RawRepresentable where RawValue == String, Self: LocalizedError {
    public var errorDescription: String? {
        return self.rawValue;
    }
}

Above only adds logic to enums that already extend LocalizedError (but one could remove "Self: LocalizedError" part, to make it apply to any string-enum).

#2 What if we need additional context, like FileNotFound with file-path associated? see my other post for that:

https://stackoverflow.com/a/70448052/8740349

Basically, copy and add LocalizedErrorEnum from above link into your project once, and reuse as many times as required with associative-enums.

1
  • d= (◕‿↼ ) For anyone who doesn't like copy/paste (or thinks extensions could conflict later).
    – Top-Master
    Jun 23, 2021 at 0:07
3

I like @Alexander-Borisenko's answer, but the localized description was not returned when caught as an Error. 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

Throwing code should make clear whether the error message is appropriate for display to end users or is only intended for developer debugging. To indicate a description is displayable to the user, I use a struct DisplayableError that implements the LocalizedError protocol.

struct DisplayableError: Error, LocalizedError {
    let errorDescription: String?

    init(_ description: String) {
        errorDescription = description
    }
}

Usage for throwing:

throw DisplayableError("Out of pixie dust.")

Usage for display:

let messageToDisplay = error.localizedDescription
2

First, let's see LocalizedErrorEnum's usage examples, then how to make those samples work (in Sorce-code section).

Usage

do {
    let path = "/my/path/to/file.txt";
    throw MyErrorCategory.FileNotFound(
        atPath: path
    );
} catch {
    print(error.localizedDescription);
}

Output:

Failed to find file. {
  atPath: /my/path/to/file.txt
}

Definition:

public enum MyErrorCategory: LocalizedErrorEnum {
    case FileNotFound(String = "Failed to find file.", atPath: String)
    case Connection(String = "Connection fail - double check internet access.")
}

The first argument is treated as message (in LocalizedErrorEnum enum).

Features required (background)

#1 Firstly, I want messages without copy/pasting, and that with ability to catch a group of different error-cases, without listing each-case (solution, enum is pretty unique without copy/paste need, and each enum can be considered another group).

#2 Secondly, some errors like "FileNotFound" need to have variable context/details, like for file-path (but Raw-Value enum does not support instance-variables, and unlike #1, the built-in enum is not the solution).

#3 Lastly, I want to be able to catch each case separately, NOT catching entire struct and/or class then doing switch inside the catch, and want to avoid forgeting the rethrow of cases we don't handle.

Source-code (solution meeting requirements)

Simply, copy and add LocalizedErrorEnum from below into your project once, and reuse as many times as required with associative-enums.

public protocol LocalizedErrorEnum: LocalizedError {
    var errorDescription: String? { get }
}

extension LocalizedErrorEnum {
    public var errorDescription: String? {
        if let current = Mirror(reflecting: self).children.first {
            let mirror = Mirror(reflecting: current.value);
            // Initial error description.
            let message = mirror.children.first?.value as? String
                ?? current.label ?? "Unknown-case";
            var context = "";
            // Iterate additional context.
            var i = 0;
            for associated in mirror.children {
                if i >= 1 {
                    if let text = associated.value as? String {
                        context += "\n  ";
                        if let label: String = associated.label {
                            context += "\(label): "
                        }
                        context += text;
                    }
                }
                i += 1;
            }
            return context.isEmpty ? message : (
                message + " {" + context + "\n}"
            );
        }
        return "\(self)";
    }
}

Note that as mentioned on my profile, using above code under Apache 2.0 license is allowed as well (without attribution need).

See also my other answer if you don't need additional context-variable with error (or for a comparison with other approaches).

1

I would like to suggest a variation of some of the proposed solutions:

public enum MyError: Error {
    var localizedDescription: String {
        get {
            switch(self) {
                case .network(let message, let code):
                    return "\(message) (\(code))"
                case .invalidInput(message: let message):
                    return message
            }
        }
    }
    case network(message: String, code: Int)
    case invalidInput(message: String)
}

It's a little more work to create but it provides the best of all worlds:

  • It's an enum so it can be used in a switch statement.
  • All the errors must be created with a message that can be a different one even for the same types of error (unlike enums that extend String)
  • It provides the message under the localizedDescription that every developer is expecting.
1
  • If the majority of the cases just have a message, is there a way to simplify the switch statement with a default case?
    – denver
    Jul 7 at 18:58
0

To reiterate @pj-finnegan's answer, several people's comments, and the footnote of the accepted answer…

I prefer several other answers provided here (if i'm looking for best practices). But if I'm answering the question as asked, the simplest way to do this (IFF you are are in iOS/macOS/…) is to used the bridged type NSError. (This question is tagged with iOS, so we can assume this is present.)

func myFunction(meNoLikey:Bool) throws {
    guard meNoLikey == false else {
        throw NSError(domain: "SubsystemOfMyApp", code: 99, userInfo: [NSLocalizedDescriptionKey: "My Message!"] )
    }
    // safe to carry on…
}

You can decide to have meaningful domains or codes, or not. The userInfo key NSLocalizedDescriptionKey is the only thing needed to deliver the message you request.

Look up NSError.UserInfoKey for any additional details you want to provide in the userInfo. You can also add anything you want, if you would like to deliver details to anyone catching the error.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.