Exception handling

Exception handling

One of the things I really like about Swift is how it deals with exception handling. It declaratively shows the functions which are likely to through exceptions and saves time in identifying where the exception may be coming from.

Suppose we have a function canThrow() which may throw as shown below.

    func canThrow() throws {
    	//Some logic that may result in an error
    }

Swift makes this declarative by prefixing try before the function canThrow . Making it clear to anyone reading the code which function is expected to throw an error.

    do {
    	try canThrow()
    	someOtherSafeFunction()
    
    } catch SomeError.happened {
    	dealWithIt()
    }

Leave a Reply