Is it possible to throw a "RuntimeException" in Swift without declaring it?

Ferran Maylinch picture Ferran Maylinch · Nov 29, 2015 · Viewed 9k times · Source

I would like to throw an exception from some "deep" function, so it bubbles up to another function, where I want to catch it.

f1 calls f2 calls f3 calls ... fN which may throw an error

I would like to catch the error from f1.

I've read that in Swift I have to declare all methods with throws, and also call them using try.

But that's quite annoying:

enum MyErrorType : ErrorType {
    case SomeError
}

func f1() {
    do {
        try f2()
    } catch {
        print("recovered")
    }
}

func f2() throws {
    try f3()
}

func f3() throws {
    try f4()
}

...

func fN() throws {
    if (someCondition) {
      throw MyErrorType.SomeError
    }
}

Isn't there a similar concept to the RuntimeException in Java, where throws doesn't leak all the way up the call chain?

Answer

Yes, it is possible!

Use: fatalError("your message here") to throw runtime exception