tezvyn:

do-try-catch versus Optional return types

AI-drafted, machine-checkedintermediate
WHAT IT TESTS

error modeling choices.

OUTLINE

throwing functions with do/try/catch convey why something failed via typed Error values; Optionals only say success or absence. Use throws when the caller needs the reason.

WHAT THIS TESTS It checks whether you model failure deliberately, matching the mechanism to whether the caller needs to know why something went wrong.

DO-TRY-CATCH A function declared throws can throw a value conforming to Error. Callers prefix the call with try inside a do block and handle failures in catch clauses, which can pattern-match specific error cases. This carries semantic information: the error type and associated values explain the cause, so the caller can branch, retry, or surface a precise message. try? converts a throw to nil and try! asserts success.

OPTIONAL RETURN An Optional return type encodes only two states, a value or nil. It says something is absent but never says why. It is lightweight and ideal when absence is a normal, expected outcome rather than an error.

WHEN EACH WINS Use throws when there are multiple meaningful failure reasons the caller should distinguish, such as network, decoding, or validation errors, or when you want errors to propagate up cleanly. Use Optional when the only question is whether a value exists, like a dictionary lookup, a failable initializer for an out-of-range input, or finding an element that may not be present, where nil is not exceptional.

COMMON WRONG ANSWERS Throwing for routine absence, which forces callers into do/catch for a non-error. Returning nil for genuine errors, discarding the reason and hiding bugs. Believing the two are interchangeable.

LIKELY FOLLOW-UPS What does try? do? When use Result instead? How do typed throws or rethrows fit in? How does this interact with async functions?

ONE CONCRETE EXAMPLE A JSON loader can fail because the file is missing, the bytes are malformed, or a field is invalid. Modeling it as throws lets the caller catch each case and show a targeted message or retry. By contrast a function that returns the first admin user in a list returns User? because having no admin is a perfectly normal result, not an error worth a thrown type.

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.