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. We use the try
keyword, within the do-catch
block, to identify the places in the code that may throw an error. The do-catch
block with a try
statement has 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 to use the do-catch
block by calling both the getPlayerByNumber()
and addPlayer()
methods of the BaseballTeam
structure. Let's look at the getPlayerByNumber()
method first, since it only throws one error condition:
do {
let player =...