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?
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.
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.
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.
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.
Yes, it is possible!
Use: fatalError("your message here")
to throw runtime exception
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With