Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 571
Ferran Maylinch Avatar asked Nov 29 '15 00:11

Ferran Maylinch


People also ask

Is it good practice to throw RuntimeException?

Generally speaking, do not throw a RuntimeException or create a subclass of RuntimeException simply because you don't want to be bothered with specifying the exceptions your methods can throw.

Is RuntimeException checked or unchecked?

Run-time exception is called unchecked exception since it's not checked during compile time. Everything under throwable except ERROR and RuntimeException are checked exception. Adding Runtime exception in program will decrease the clarity of program.

Does exception include RuntimeException?

Catching Exception or ThrowableCatching Exception will catch both checked and runtime exceptions. Runtime exceptions represent problems that are a direct result of a programming problem, and as such shouldn't be caught since it can't be reasonably expected to recover from them or handle them.

How do you throw a run time exception?

An exception object is an instance of an exception class. It gets created and handed to the Java runtime when an exceptional event occurred that disrupted the normal flow of the application. This is called “to throw an exception” because in Java you use the keyword “throw” to hand the exception to the runtime.


Video Answer


1 Answers

Yes, it is possible!

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

like image 103
Максим Мартынов Avatar answered Sep 30 '22 08:09

Максим Мартынов