0Pricing
Zig Academy · Lección

Recuperarse con catch

Proporcione una alternativa cuando se produzca un error.

Recuperarse con catch es una lección gratuita de Zig Academy en CoddyKit. Esta es la lección 1 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.

Errors Need a Plan

A function can return an error union like !u32. Before you use the result you must decide what happens on the failure path.

Meet catch

The catch operator turns an error union into a plain value by giving a fallback to use whenever the call returns an error.

const n = parse(text) catch 0;

The Fallback Replaces the Error

If the call succeeds you get the real value. If it errors you get the right side of catch instead, so n is always a usable number.

const n = parse(text) catch -1;

catch Is an Expression

Because catch yields a value, you can drop it inline anywhere a value is expected, like straight into a function argument.

print(parse(text) catch 0);

Capture the Error

Add a pipe capture to inspect what went wrong. The name inside the bars holds the specific error value that was returned.

const n = parse(text) catch |err| {
    log(err);
    return 0;
};

catch Can Run a Block

The right side of catch may be a whole block. Use it to log, compute a fallback, or break out of a loop before continuing.

const v = open(path) catch |e| blk: {
    break :blk fallback;
};

catch Can Return Early

You can return from inside catch to leave the function when recovery is impossible. The code after it never runs on error.

const f = open(path) catch return error.MissingFile;

catch unreachable

Writing catch unreachable asserts the call cannot fail. In a safe build a real error here panics instead of being ignored.

const n = parse("42") catch unreachable;

Use unreachable Carefully

Reach for catch unreachable only when an error is truly impossible. If you are unsure, supply a real fallback instead.

catch vs try

Use catch when you can handle the error here and now. Use try when you would rather pass the error up to the caller.

Recovery Is Explicit

Every error union forces a choice, so a failure can never be silently dropped. With catch you decide exactly how to recover.

Quick Check

You want to keep going with a safe default when a call fails. Which expression fits?

Recap

You used catch to recover from errors with a fallback, a block, an early return, or an assertion. Failure is always handled on purpose. ✅

Preguntas frecuentes

¿La lección «Recuperarse con catch» es gratis?

Sí — el texto completo de «Recuperarse con catch» 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 «Recuperarse con catch»?

Proporcione una alternativa cuando se produzca un error. 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 1 de 4.

¿Cuánto tiempo toma la lección «Recuperarse con catch»?

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. Recuperarse con catch
  2. Usar switch con errores específicos
  3. errdefer para limpiar tras un fallo
  4. Envolver y volver a lanzar errores
← Volver a Zig Academy