Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An elegant way to ignore any errors thrown by a method

I'm removing a temporary file with NSFileManager like this:

let fm = NSFileManager() fm.removeItemAtURL(fileURL) // error: "Call can throw but it is not marked with 'try'" 

I don't really care if the file is there when the call is made and if it's already removed, so be it.

What would be an elegant way to tell Swift to ignore any thrown errors, without using do/catch?

like image 936
Desmond Hume Avatar asked Sep 25 '15 18:09

Desmond Hume


People also ask

Which keyword is used to ignore the exception from any method?

In the catch block you can mention the exception and ignore keyword for that exception.

How do you handle errors in Java?

The try-catch is the simplest method of handling exceptions. Put the code you want to run in the try block, and any Java exceptions that the code throws are caught by one or more catch blocks. This method will catch any type of Java exceptions that get thrown. This is the simplest mechanism for handling exceptions.

How do I bypass an exception?

Sometimes, you may want to ignore an exception thrown by your Java program without stopping the program execution. To ignore an exception in Java, you need to add the try... catch block to the code that can throw an exception, but you don't need to write anything inside the catch block.

How do you implement your error handling?

If you can sense what type of exceptions may arise, create a small separate code to rebound from this state. Be specific about all different exceptions. Depending on your program, these exceptions may hamper your data if not written well. Try using statements that can make error handling for you.


1 Answers

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 the try? expression, the value of the expression is nil.

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.

like image 184
Martin R Avatar answered Sep 28 '22 09:09

Martin R