0Pricing
Zig Academy · Урок

Выводимые наборы ошибок

Позвольте Zig самостоятельно собрать ваши ошибки.

«Выводимые наборы ошибок» — бесплатный урок Zig Academy на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Zig Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Zig Academy содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Listing Errors Is Tedious

Naming every error a function might return can be a chore, especially when it calls other fallible functions. Zig can infer the set.

Leave the Set Off

Write just !T with nothing before the bang. Zig studies the function body and figures out every error it can produce.

fn parse(s: []const u8) !u32 {
    // ...
}

The Compiler Collects Them

Each try and each returned error inside the body is gathered automatically into one inferred error set for that function.

if (s.len == 0) return error.Empty;

It Stays Accurate

Add a new failing call later and the inferred set grows to include it. You never forget to update a hand-written list.

Inference Across Calls

If your function uses try on another fallible call, that callee's possible errors are folded into your inferred set as well.

const f = try open(path);

Explicit Sets Still Win

Sometimes you want a fixed public contract. Naming the set before ! forbids any error outside it, which inference will not do.

fn load() FileError!Data {}

Trade-Off in One Line

Inferred sets are convenient and self-updating; explicit sets are precise and stable. Pick by whether the contract must stay frozen.

Inspect with @errorReturnTrace

You can still reason about errors at runtime. In debug builds Zig keeps an error return trace showing where a failure began.

Great for Internal Helpers

Inference shines on private helper functions where a strict public API is not needed. Let Zig handle the bookkeeping there.

Still Fully Checked

Inferred or explicit, every error must still be handled by callers. Inference saves typing, not safety; the compiler stays strict.

A Pragmatic Default

Many Zig functions simply use !T and let inference work. Reserve named sets for the boundaries you want to lock down.

Quick Check

A function is declared with the return type !u32 and no error set before the bang. What does Zig do?

Recap

You saw inferred error sets via bare !T, how they grow with the body, and when an explicit set is the better choice. ✅

Часто задаваемые вопросы

Урок «Выводимые наборы ошибок» бесплатный?

Да — полный текст урока «Выводимые наборы ошибок» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Zig Academy, подпишись на CoddyKit PRO. Курс Zig Academy содержит 4 уроков всего.

Чему я научусь в уроке «Выводимые наборы ошибок»?

Позвольте Zig самостоятельно собрать ваши ошибки. Ты практикуешь Zig Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Zig Academy?

Предыдущий опыт не требуется. Zig Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.

Сколько времени занимает урок «Выводимые наборы ошибок»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Zig Academy?

Да. Каждый урок Zig Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Наборы ошибок и объединение !T
  2. Возврат ошибок из функций
  3. Передача сбоев с помощью try
  4. Выводимые наборы ошибок
← Назад к Zig Academy