Professional Documents
Culture Documents
if you want to throw an error you have to specify Throws to the end of method
or initialiser of 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 {
**************************************************************************
**
//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")
**************************************************************************
**