You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

0 D铆as
3 Hrs
14 Min
48 Seg

Propagaci贸n de errores

23/25
Resources

How to create custom errors in Swift?

Creating custom errors in Swift is essential for improving error handling in your applications. This allows you to provide more descriptive error messages that benefit both developers and end users. Let's start by defining a custom error in Swift. We will use the enum keyword to create these errors, and have them implement the Error and LocalizedError protocols.

Defining a custom error enum

To create a custom error enum, start with defining an enum that implements the appropriate protocols. This will allow you to specify different error cases that you want to handle in your application.

public enum ManagerError: Error, LocalizedError { case studentNotAddError case subjectNotAssignedError case reportNotFoundError case maxStudentsReachedError(max: Int) public var errorDescription: String? { switch self { case .studentNotAddError: return "Student could not be added." case .subjectNotAssignedError: return "Could not assign subject." case .reportNotFoundError: return "The report could not be found, since the list of students is empty." case .maxStudentsReachedError(let max): return "The maximum number of students \(max) has been reached." } } } } } }

Error description implementation.

The LocalizedError protocol allows defining an optional errorDescription property. This property provides more detailed error descriptions, which can be used in the user interface or in system feedback. We use a switch to return descriptions based on each enum case.

How to throw errors in Swift methods?

Once errors are defined, it is crucial to know when and how to throw them in your methods. In Swift, we use the throws keyword to indicate that a method can throw an error.

Specifying methods that throw errors

Before throwing errors, define which methods in your protocol can cause errors. Here we use the throws modifier in the method declaration. Look at an example where a method to insert students throws an error if something goes wrong.

func insertStudent(_ student: Student) throws { if student == nil { throw ManagerError.studentNotAddError } // Check the maximum number of students before adding a new one if students.count >= maxStudents { throw ManagerError.maxStudentsReachedError(max: maxStudents) } students.append(student) }

Example of use in student management

In our example of the student manager(StudentsManager), we throw specific errors depending on the operations attempted.

func assignSubjectToStudent(_ subject: Subject, student: Student) throws { guard student.subjects.contains(subject) else { throw ManagerError.subjectNotAssignedError } student.subjects.append(subject) } func generateReport() throws -> String { guard !students.isEmpty else { throw ManagerError.reportNotFoundError } // Generate and print reports }

How to improve error handling?

Handling and catching thrown errors will improve the stability and user experience in your application. Proper implementation of these techniques will allow you to catch specific errors efficiently.

  1. Use do-catch to handle errors: Capture and handle errors in the catch block, providing a controlled flow of execution.
  2. Clear descriptions: Provide a clear and concise description of each error, as we have done with errorDescription.
  3. Monitor performance: Test and profile your application to identify areas that might cause errors more frequently.

Contributions 0

Questions 0

Sort by:

Want to see more contributions, questions and answers from the community?