Search Your Question

How to handle error in Swift?

Ans : 

Error Protocol is just a type for representing error values that can be thrown.

Lets declare our custom error enum by confirming Error protocol.

enum UserDetailError: Error {
        case noValidName
        case noValidAge
}

Now we make one function that throw our error type.

func userTest(age: Int, name: String) throws {
    
    guard age > 0 else {
           throw UserDetailError.noValidAge
    }
    
    guard name.count > 0 else {
           throw UserDetailError.noValidName
    }
}

In function signature, throws keyword is used and in function throw keyword is used to throw error.

Now we cal our function userTest that can throw error.

do{
       try userTest(age: -1, name: "")
}
catch UserDetailError.noValidName
{
        print("The name isn't valid")
}
catch UserDetailError.noValidAge
{
         print("The age isn't valid")
}
catch let error {
          print("Unspecified Error: \(error)")
}


Swift try, try? and try! 

  • Swift try is the most basic way of dealing with functions that can throw errors. try is only used within a do-catch block. However, try? and try! can be used without it.
  • try? is used to handle errors by converting the error into an optional value. This way if an error occurs, the function would return a nil and we known Optionals can be nil in Swift. Hence for try? you can get rid of do-catch block. 
  • try! is used to assert that the error won’t occur. Should be only used when you’re absolutely sure that the function won’t throw an error. Like try?, try! works without a do-catch block.

var t1 = try? Student(name: nil)
var t2 = try! Student(name: "Anupam")



No comments:

Post a Comment

Thanks