Course of Raku / Objects, I/O, and exceptions / Exceptions

The CATCH phaser

The try block is convenient, but it treats the whole block as one unit: either it works or it does not. The CATCH phaser gives you finer control — it lets you handle an exception inside the block where it happened, and decide what to do.

CATCH is a phaser, like the ones you met in the section about control flow. You write it anywhere inside a block; it runs only if an exception is thrown there. The exception is available as the topic $_:

{
    die 'Boom!';

    CATCH {
        default {
            say 'Caught: ' ~ .message;
        }
    }
}

say 'after';

The program prints:

Caught: Boom!
after

The default block inside CATCH handles any exception. Once it has run, the exception is considered handled, so the program does not stop — execution carries on after the enclosing block, which is why after is printed.

Without the CATCH, the die would have ended the program before after could be reached.

Practice

Complete the quiz that covers the contents of this topic.

Exercises

This section contains 3 exercises. Examine all the topics of this section before doing the coding practice.

  1. Handle and continue
  2. Survive a loop
  3. Report and recover

Course navigation

Quiz — try   |   Handle and continue