You are on page 1of 3

Error Handling:

– we can achieve this using Throws

– we can specify Throws to functions and initialisers (classes)

if you want to throw an error you have to specify Throws to the end of method
or initialiser of class

**************************************************************************
**

enum UserDetailError: Error {


case noValidName
case noValidAge
}

//adding throws to function

func userTest(age: Int, name: String) throws {

guard age > 0 else{


throw UserDetailError.noValidAge
}

guard name.count > 0 else{


throw UserDetailError.noValidName
}
}

//adding throws to initialisers in class

class Student {
var name: String?
init(name: String?) throws {
guard let name = name else{
throw StudentError.invalid("Invalid")
}
self.name = name }
func myName(str: String) throws -> String {

guard str.count > 5


else{
throw StudentError.tooShort
}

return "My name is \(str)"


}
}

**************************************************************************
**
//using Trows functions or classes with help of Do-try-catch

note: if you specify Throw to function or initialiser you have to use try
keyword to call that Throw Function or Class

**************************************************************************
**

//calling functions

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)")
}

//initialising class
do{
var s = try Student(name: nil)
}
catch let error
{
print(error)
}

//prints
//invalid("Invalid")

**************************************************************************
**

You might also like