O'Reilly logo

Mastering Swift 4 - Fourth Edition by Jon Hoffman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Catching errors

When an error is thrown from a function, we need to catch it in the code that called it; this is done using the do-catch block. The do-catch block takes the following syntax:

do { 
  try [Some function that throws] 
  [code if no error was thrown] 
} catch [pattern] { 
  [Code if function threw error] 
} 

If an error is thrown, it is propagated out until it is handled by a catch clause. The catch clause consists of the catch keyword, followed by a pattern to match the error against. If the error matches the pattern, the code within the catch block is executed.

Let's look at how we can use the do-catch block by calling both the getPlayerByNumber() and addPlayer() methods of the BaseballTeam structure. Let's look at the getPlayerByNumber() ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required