Error Handling Flashcards
What is error handling?
Error handling is the process of responding to and recovering from error conditions in your program
What is an error?
Code that produces an incorrect or unexpected result
What are the 4 ways to handle errors in swift?
Propagating the errors using throwing functions.
Handling errors using do-catch
Converting errors to optional values
Disabling Error Propagation
How do you propagate errors using throwing functions(show an example)?
You write the throws keyword in the function’s declaration after its parameters Func canThrowErrors() throws -> String Also need the word throw when selecting what error to throw (example)
How do you test a throwing function?
You have to use the try keyword
example
How do you handle errors using do-catch?
If an error is thrown by the code in the do clause, it passes it to catch clause to see what errors the clause can handle.
What happens if the catch clause doesn’t have a pattern?
The clause matches any error and binds the error to a local constant named error.
How do you convert errors to optional values?
You use try? to handle an error by converting it to an optional value
If an error is thrown while evaluating the try? expression, the value of the expression is nil
In what order are defer statements executed?
Reverse order
What language construct allows us to easily deal with domain errors in Swift?
Optionals
An error that occurs because a result is outside the accepted range of values is known as a
Domain error
Errors that are raised before your code is run is commonly known as a:
Compiler error
Where do we add the throws keyword to indicate that the function can throw an error?
After the parameter list and before the return type
TF: The throw keyword is a control transfer statement and exits the current scope
True
To allow an object to model an error, we conform to the ___________ protocol
Error
TF: An error is said to occur when you get an incorrect or unexpected result
True
TF: By default all functions throw errors
False
To call a throwing function we need to mark it with a certain keyword to indicate that this function can return an error. What is the keyword?
Try
TF: A catch clauses cannot pattern match on different error cases like a switch statement
False
Where are errors thrown from a function handled?
Catch clause
The call to a throwing function along with the happy path of code is encapsulated in a _______ clause.
Do
To execute statements as we leave the current scope we use a ________ statement
Defer
In Swift, you can indicate what kind of error is being thrown from a function, i.e, the function preserves type information of thrown errors.
False, We can only indicate an error is thrown, not the type of error
When an error is thrown from inside a do clause, what happens?
The error is propagated to its outer scope and handled by a catch clause.