do-catch Statement in Swift Tutorial 🎯

beginner
9 min

do-catch Statement in Swift Tutorial 🎯

Welcome back, Swift learners! Today, we're diving into one of Swift's essential error-handling mechanisms - the do-catch statement. This powerful tool helps us manage and recover from runtime errors, making our code more robust and reliable.

What is the do-catch Statement? 💡

In simple terms, the do-catch statement is a structure that allows us to handle and recover from thrown exceptions, or errors, in our Swift code. By using this mechanism, we can write more resilient code, capable of handling unexpected situations gracefully.

Breaking it Down: The Components 📝

The do-catch statement consists of three main parts:

  1. do: This is where the code that might throw an error is placed.
  2. catch: This is where the error-handling code goes. We can have multiple catch blocks for different types of errors.
  3. throw: We use the throw keyword to intentionally create an error, which can be caught and handled.

Let's Write Some Code! ✅

Now that we understand the components, let's put them into practice. Here's a simple example of using the do-catch statement:

swift
do { // Some code that might throw an error let number = -5 if number < 0 { throw NSError(domain: "MyDomain", code: 1, userInfo: nil) } } catch { print("Oops! An error occurred.") }

In this example, we're checking if a number is less than zero, and if it is, we're throwing an error. The catch block then catches the error and prints a friendly error message.

Catching Specific Errors 💡

We can also catch specific types of errors using a catch block with a specific error type:

swift
do { // Some code that might throw an error let number = -5 if number < 0 { throw NSError(domain: "MyDomain", code: 1, userInfo: nil) } } catch NSError { print("Oops! A specific error occurred.") }

In this example, we're only catching NSError and printing a different error message.

Try-Catch-Finally Block 📝

Swift also supports a try-catch-finally block, which allows us to execute code after the do block, regardless of whether an error occurred or not.

swift
do { // Some code that might throw an error try someCodeThatThrows() } catch { print("Oops! An error occurred.") } finally { print("This code will always run, whether an error occurred or not.") }

Quiz Time! 🎯

Quick Quiz
Question 1 of 1

What is the purpose of the `do-catch` statement in Swift?

Keep coding, and we'll see you in the next lesson! 🚀