0Pricing
Zig Academy · Lección

Devolver errores desde funciones

Haga explícito el fallo en las firmas.

Devolver errores desde funciones es una lección gratuita de Zig Academy en CoddyKit. Esta es la lección 2 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Zig Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Zig Academy incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

Failure in the Signature

When a function can fail, say so in its return type. An error union like ParseError!u32 warns every caller up front.

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

Return the Success Value

On the happy path you just return the payload as normal. Zig wraps that plain value into the success side of the union for you.

return 42;

Return an Error Instead

To fail, return one of your errors in the same spot. The single return statement decides which side of the union you produce.

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

One Return, Two Outcomes

A function with an error union can return a value in one branch and an error in another. Both satisfy the declared type.

if (ok) return value;
return error.Failed;

Void Plus Errors

A function that does work but yields no value can still fail. Use !void so it returns nothing on success or an error on failure.

fn save() !void {
    // ...
}

Errors Bubble at the Call Site

When you call a fallible function, you receive an error union too. You cannot ignore it; the compiler makes you handle it.

const n = parse(input);

Capture Errors with if

An if can split the union: capture the value in the main branch and the error after else, naming each with a pipe.

if (parse(input)) |n| {
    use(n);
} else |err| {
    report(err);
}

Name the Error Set Precisely

Listing the exact set before ! keeps your contract honest. Callers learn the full list of failures without reading the body.

fn open(p: []const u8) FileError!File {}

Errors Cross Function Boundaries

An error returned deep inside your code travels outward only when each function in the chain declares it can fail too.

Make Failure Explicit

This is the heart of Zig error handling: failure is never hidden. The signature is a promise about what can go wrong.

Compiler Has Your Back

Forget to handle a returned error and the build fails. Zig refuses to let a possible failure silently slip through.

Quick Check

A function does work but returns no useful value, yet it might fail. What return type fits?

Recap

You declared fallible functions with !T, returned values or errors from one return, and saw the compiler force callers to handle them. ✅

Preguntas frecuentes

¿La lección «Devolver errores desde funciones» es gratis?

Sí — el texto completo de «Devolver errores desde funciones» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Zig Academy, actualiza a CoddyKit PRO. El curso de Zig Academy incluye 4 lecciones en total.

¿Qué aprenderé en «Devolver errores desde funciones»?

Haga explícito el fallo en las firmas. Practicas Zig Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Zig Academy?

No se requiere experiencia previa. Zig Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 2 de 4.

¿Cuánto tiempo toma la lección «Devolver errores desde funciones»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Zig Academy?

Sí. Cada lección de Zig Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Conjuntos de errores y la unión !T
  2. Devolver errores desde funciones
  3. Propagar fallos con try
  4. Conjuntos de errores inferidos
← Volver a Zig Academy