Swift — Error Handling
Defining errors
enum NetworkError: Error {
case badURL
case noData
case decodingFailed
case serverError(statusCode: Int)
}
Throwing functions
func fetchData(from urlString: String) throws -> String {
guard let url = URL(string: urlString) else {
throw NetworkError.badURL
}
// Simulate network request
return "Data from \(url)"
}
try and catch
do {
let data = try fetchData(from: "https://example.com")
print(data)
} catch NetworkError.badURL {
print("Invalid URL")
} catch NetworkError.serverError(let code) {
print("Server error: \(code)")
} catch {
print("Unexpected error: \(error)")
}
try?
let data = try? fetchData(from: "https://example.com")
print(data ?? "No data")
try!
// Use only when you're sure it won't fail
let data = try! fetchData(from: "https://example.com")
Result type
enum Result<Success, Failure: Error> {
case success(Success)
case failure(Failure)
}
func divide(_ a: Int, by b: Int) -> Result<Int, Error> {
guard b != 0 else {
return .failure(NetworkError.badURL)
}
return .success(a / b)
}
switch divide(10, by: 3) {
case .success(let result):
print("Result: \(result)")
case .failure(let error):
print("Error: \(error)")
}
Mini Practice
Write Swift code that:
- Defines a custom error enum
- Creates a throwing function
- Uses
do-try-catchfor error handling - Uses
try?andResulttype
Up Next
In the next lesson, you'll learn about Generics — writing reusable code.
Related Topics
Frequently Asked Questions about Error Handling
What is Error Handling in Swift?
Error Handling is a fundamental concept in Swift. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Error Handling?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Error Handling.
Why is Error Handling important in Swift?
Error Handling is essential for Swift development. Understanding this concept will help you write better code and solve real-world problems more effectively.