Swift - Day 3 : Exception handling
Though there’s nothing exceptionally new to me about how Swift deals with exceptions, I do have to say that I prefer it’s way of dealing with functions that throw an error. I find them to be easier to read compared to languages like java.
Suppose we have a function canThrow()
which may throw as shown below.
func canThrow() throws {
//Some logic that may result in an error
}
What I like about Swift is the way the function is called in a different part of the code that handles/catches the error.
do {
try canThrow()
someOtherSafeFunction()
} catch SomeError.happened {
dealWithIt()
}
By having try before the function that could potentially throw an error,it is clear to anyone reading the code where an exception may come from.