Генерация ошибки
Сообщайте о возникшей проблеме.
«Генерация ошибки» — бесплатный урок Mojo Academy на CoddyKit. Это урок 1 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Mojo Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Mojo Academy содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
When Things Go Wrong
Sometimes a function hits a situation it cannot handle, like a missing file or bad input. Mojo lets you signal that with an error. ⚠️
The raise Keyword
To signal a failure, you use the raise keyword. It stops the current work and reports that something went wrong.
raise Error("something went wrong")Errors Carry a Message
When you raise, you pass a short message describing the problem. Whoever handles the error can read that text.
raise Error("file not found")Raising Inside a Function
A function can raise when its input is invalid. Here a negative amount is rejected before any further work happens.
fn withdraw(amount: Int) raises:
if amount < 0:
raise Error("amount must be positive")Raising Stops Execution
Once raise runs, the rest of the function is skipped. Control jumps out, looking for code that can deal with the error.
Why Not Just Return -1?
Returning a magic value like -1 is easy to ignore. An error cannot be silently skipped, making failures far harder to miss.
Errors Travel Up
An unhandled error keeps moving up through the callers until something catches it. This is called propagation.
Guarding Your Inputs
Raising early on bad input is a clean habit. Check the values first, then raise before the real logic ever runs.
if name == "":
raise Error("name is required")One Clear Reason
Give each raise a clear, specific message. Good wording turns a crash into a helpful clue for whoever debugs it.
Errors Are Not Crashes
A raised error is a structured signal, not a random crash. Your program can recover from it instead of just dying.
Raise When You Can't Continue
The rule of thumb: raise only when a function truly cannot finish its job correctly. Don't raise for normal outcomes.
Quick Check
Think about what the raise keyword actually does in Mojo.
Recap
You learned to signal failures with raise, attach a clear message, and let errors stop bad work instead of returning magic values. 🎯
Часто задаваемые вопросы
Урок «Генерация ошибки» бесплатный?
Да — полный текст урока «Генерация ошибки» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Mojo Academy, подпишись на CoddyKit PRO. Курс Mojo Academy содержит 4 уроков всего.
Чему я научусь в уроке «Генерация ошибки»?
Сообщайте о возникшей проблеме. Ты практикуешь Mojo Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Mojo Academy?
Предыдущий опыт не требуется. Mojo Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 1 из 4.
Сколько времени занимает урок «Генерация ошибки»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Mojo Academy?
Да. Каждый урок Mojo Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Генерация ошибки
- Перехват с try/except
- Аннотация raises
- Очистка с finally