An elegant way to ignore any errors thrown by a method
If you don't care about success or not then you can call
let fm = NSFileManager.defaultManager()
_ = try? fm.removeItemAtURL(fileURL)
From "Error Handling" in the Swift documentation:
You use
try?
to handle an error by converting it to an optional value.
If an error is thrown while evaluating thetry?
expression, the value
of the expression isnil
.
The removeItemAtURL()
returns "nothing" (aka Void
), therefore the return value of the try?
expression is Optional<Void>
.
Assigning this return value to _
avoids a "result of 'try?' is unused" warning.
If you are only interested in the outcome of the call but not in
the particular error which was thrown then you can test the
return value of try?
against nil
:
if (try? fm.removeItemAtURL(fileURL)) == nil {
print("failed")
}
Update: As of Swift 3 (Xcode 8), you don't need the dummy assignment, at least not in this particular case:
let fileURL = URL(fileURLWithPath: "/path/to/file")
let fm = FileManager.default
try? fm.removeItem(at: fileURL)
compiles without warnings.
What to do with Swift's try? that cause Result of try? is unused?
As your requirement, "At the same time I don't care about the exception that may be thrown, I just want to call method", do this:
try! managedObjectContext.save()
But it will crash if an error is thrown. So, use below code snip for safe:
_ = try? managedObjectContext.save()
How to ignore Exceptions in Java
There is no way to fundamentally ignore a thrown exception. The best that you can do is minimize the boilerplate you need to wrap the exception-throwing code in.
If you are on Java 8, you can use this:
public static void ignoringExc(RunnableExc r) {
try { r.run(); } catch (Exception e) { }
}
@FunctionalInterface public interface RunnableExc { void run() throws Exception; }
Then, and implying static imports, your code becomes
ignoringExc(() -> test.setSomething1(0));
ignoringExc(() -> test.setSomething2(0));
Use the try? operator to make the code more concise
In Swift 3 it is legal to ignore the result without the extra assignment. This compiles just fine, with no warning, in the Xcode 8 GM:
try? FileManager.default.removeItem(atPath: destination)
(Earlier, by the way, I asked about this on bugs.swift.org, and was told directly that this _ = try?
syntax is regarded as correct and is a small price to pay for acknowledging to the compiler — and yourself — that you are deliberately ignoring the returned value. So what you are doing is just fine while you remain in the Swift 2 world!)
What is an elegant way to wrap an error an rethrow in both cases?
try...catch
and throw
are expressions in Kotlin, so you can do:
val result =
try {
callMethod()
} catch (e: SomeException) {
null
} ?: throw UserFiendlyException("cannot process you, try again pls")
The try...catch
will produce null
if either callMethod
returns null. or if an exception occurred. We check if it is null using ?:
, and if it is, we throw the user friendly exception.
result
will end up having a non nullable type.
How to properly ignore exception in Java?
The only way to ignore an exception is to catch & swallow it, being very specific on the exception of course, you wouldn't want to catch Exception e
, that would be a very bad idea.
try{
... //code
}
catch( VerySpecificException ignore){
Log(ignore);
}
Logging is obviously optional but a good practice.
How to properly ignore exceptions
try:
doSomething()
except Exception:
pass
or
try:
doSomething()
except:
pass
The difference is that the second one will also catch KeyboardInterrupt
, SystemExit
and stuff like that, which are derived directly from BaseException
, not Exception
.
See documentation for details:
try
statement- exceptions
However, it is generally bad practice to catch every error - see Why is "except: pass" a bad programming practice?
How do I ignore an exception?
scala.util.control.Exception.ignoring(classOf[ExceptionType]) {
... // Some throwing code
}
Java 8: How do I work with exception throwing methods in streams?
You need to wrap your method call into another one, where you do not throw checked exceptions. You can still throw anything that is a subclass of RuntimeException
.
A normal wrapping idiom is something like:
private void safeFoo(final A a) {
try {
a.foo();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
(Supertype exception Exception
is only used as example, never try to catch it yourself)
Then you can call it with: as.forEach(this::safeFoo)
.
Related Topics
Create Singleton of a Viewcontroller in Swift 3
Locationmanager:Didenterregion Not Called When a Beacon Is Detected
Present Uialertcontroller from Appdelegate
How to Pass Information Between Storyboard Segues
How to Only Disable Scroll in Scrollview But Not Content View
New Itunes Connect Interface -- Should It Immediately Be Seen on "Prerelease"
Xcode Warning When Using Mapkit and Corelocation
How to Use Dark Mode in Simulator iOS 13
An Elegant Way to Ignore Any Errors Thrown by a Method
How to Execute Some Code After a Segue Is Done
How to Connect Multiple Buttons in a Storyboard to a Single Action
Error in Xcode 6 - View Controller Does Not Have an Outlet Named (Subview)