Swift is a programming language for developing apps for iOS, macOS, watchOS, and tvOS. Nonetheless, many aspects of Swift will be familiar to you if you've worked with C or Objective-C before.
In this blog, we will focus on how swift manages to handle errors in code.
Let’s briefly learn about error handling mechanisms in swift.
Error Handling
The process of responding to and recovering from erroneous conditions in the code is known as Error Handling. Swift has built-in support for throwing, catching, propagating, and manipulating recoverable errors.
Some processes aren't always guaranteed to finish or give beneficial results. It's often necessary to understand why an operation fails so that your code can respond appropriately.
Consider the work of reading and processing data from a disk file as an example. This task can fail for various reasons, including the file not existing at the specified location, not having read permissions, or not being encoded in a compatible format. Differentiating between these scenarios allows a program to fix some errors and notify the user about any errors it can't fix.
Let’s take an example of an Error code:-
var a = 100
var b = 0
// Trying to divide a number by 0
var res = a / b // error code
In the above code, we can see that we are trying to divide a number by 0, which is definitely going to throw an error. And this type of error causes the abnormal termination of the program.
Steps For Handling Error In Swift
The different steps for error handling in swift are given below:-
1.) Create an enum to represent the different types of errors.
2.) Using the throws keyword, create a throwing function.
3.) Call the function using the try keyword.
4.) To handle all errors, wrap the code with a try in the do{...} block and add the catch{...} block.
Let’s discuss the above steps one by one.
Creating enum of Errors
We need to create an enum in Swift that represents the different types of errors we can experience while writing the application.
To be able to throw an error value inside the function, the enum we define must follow the Error protocol.
Let’s take an example:-
enum DivisionError: Error {
case divisionByZero
}
In the above example, we have named the enum DivisionError and given it the value divisionByZero.
We may now throw the enum's error value because DivisionError conforms to the Error protocol.
Creating a Throwing Function
To throw errors, we need to use the throws keyword to build a throwing function.
Then, within the code, we utilize the throw keyword to throw a specific error represented by the enum.
Let’s take an example:-
// Creating a throwing function using the throws keyword
// a->numerator and b->denominator
func division(a: Int, b: Int) throws {
// throw error if divide by 0
if b == 0 {
throw DivisionError.divisionByZero
}
}
In the above code, we can see that using the throws keyword, we've created a throwing function called division(). If denominator == 0, the function returns the DivisionError enum value divisionByZero.
If the error condition is met, the function now throws an error based on the value given during the function call.
Function Call Using try Keyword
When using the throwing function in Swift, we use the try keyword. It denotes the possibility of an error being thrown by a function.
Let’s take an example:-
// Calling throwing function using try keyword
// a->numerator and b->denominator
try division(a: 100, b: 0)
The error-handling procedure, on the other hand, is still incomplete. If we run the program right now, we'll get the following error: An error was thrown and was not caught.
So, we use the do-catch statement to catch the thrown error.
Handling Errors Using do-catch
To handle all errors, we wrap the try code in the do block and add the catch block.
Let’s take an example:-
// a->numerator and b->denominator
do {
try division(a: 100, b: 0)
...
}
catch DivisionError.divisionByZero {
// statement
}
In the above code, we've called the throwing function division() from the do block, and we've added a catch block to capture any errors the function might throw.
The catch block above is invoked based on the DivisionError enum value.
This is the final step in dealing with any possible errors in our code.
Final Code: Handling Division Error
By combining the above 4 steps code, the final error handling code for division by zero error is given below:-
// Creating an enum with error values
enum DivisionError: Error {
case divisionByZero
}
// Creating a throwing function using throws keyword
// a->numerator and b->denominator
func division(a: Int, b: Int) throws {
// Throw error if divide by 0
if (b == 0) {
throw DivisionError.divisionByZero
}
else {
let res = a / b
print("Value = ", res)
}
}
// Calling a throwing function from do block
do {
try division(a: 100, b: 0)
print("Hurray! It is a valid division")
}
// Catch error if function throws an error
catch DivisionError.divisionByZero {
print("Oops! Error: Denominator Cannot be 0")
}
Output:
When the value of the denominator is 0, i.e., b=0.
When the value of the denominator is not zero, i.e., b=10.
Disable Error Handling
In Swift, we can sometimes be sure that the throwing function will not throw an error at runtime.
In that situation, we can use try! to disable error handling during the function call.
For Example:-
// Creating an enum with error values
enum DivisionError: Error {
case divisionByZero
}
// Creating a throwing function using throws keyword
// a->numerator and b->denominator
func division(a: Int, b: Int) throws {
// Throw error if divide by 0
if (b == 0) {
throw DivisionError.divisionByZero
}
else {
let res = a / b
print("Value = ", res)
}
}
// disable error handling
try! division(a: 100, b: 10)
Output:
In the above example, try! during the function call to disable the error handling.
Note: If we use try! and there is an error in the code, our application will crash.
Frequently asked questions
What is Swift?
Swift is a programming language for developing apps for iOS, macOS, watchOS, and tvOS.
What is Error Handling?
The process of responding to and recovering from erroneous conditions in the code is known as Error Handling.
What is the use of the throws keyword in Swift?
throws is a keyword in swift that allows us to throw errors inside a method, property, class, or struct.