UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Hacking with macOS, Project 7, do...try...catch

Forums > macOS

So, in the drag and drop section of Project 7, we create a method performExternalDrag to copy pictures into the application's data folder and then insert the pictures into the grid. The copy might not work for a variety of reasons, so we wrap the copy instruction with do { try <attempt to copy> } catch { <print an error to the console> } but then after this we go ahead and insert the item into the grid.

Now, I'm new to Swift (which is why I'm reading this course), so maybe (probably) my understanding of its exception handling is flawed, but shouldn't that insertion only get executed if the copy succeeds? Won't the presented implementation fail unpleasantly if the copy doesn't work?

3      

Yep, you're right about it going weird. In fact, you can test it by defining an error enum, something like enum TestError: Error { case foo } and then throwing it before trying to copy the file:

do {
    throw TestError.foo
    try fm.copyItem(at: sourceURL, to: destinationURL)
} catch {
    ...
}

This forces an exception instead of the copy, and you can test out the behaviour. I solved the issue just by adding a continue statement at the end of the catch block, which skips the insertion of the items when the copying fails, and it fixed the issue.

do {
    try fm.copyItem(at: sourceURL, to: destinationURL)
} catch {
    print("Error copying item from: \(sourceURL): \(error)")
    continue
}

--Jakub

3      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.