rspec/rules/S3661/swift/rule.adoc

58 lines
1.1 KiB
Plaintext
Raw Permalink Normal View History

== Why is this an issue?
2021-04-28 16:49:39 +02:00
The use of Swift 2.0's ``++try!++`` lets you execute code that might throw an exception without using the ``++do++`` and ``++catch++`` syntax normally required for such code. By using it, you're guaranteeing that the executed code will never fail. Murphy's Law guarantees you're wrong. And when it does fail, the program will exit abruptly, probably without cleaning up after itself.
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,swift]
2021-04-28 16:49:39 +02:00
----
let myvar = try! dangerousCode(foo); // Noncompliant
// ...
----
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,swift]
2021-04-28 16:49:39 +02:00
----
guard let myvar = try? dangerousCode(foo) else {
// handle error
}
// or
if let myvar = try? dangerousCode(foo); {
// ...
} else {
// handle error
}
// or
do {
let myvar = try dangerousCode(foo)
// ...
} catch {
// handle error
}
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Use "try" or "try?" here instead; "try!" disables error propagation.
=== Highlighting
``++try!++``
endif::env-github,rspecator-view[]