class Exception

Anomalous event capable of interrupting normal control-flow
class Exception {}

All exceptions that are placed into the $! variable (or into $_ in CATCH blocks) inherit from Exception. When you call die or fail with a non-Exception argument, it is wrapped into an X::AdHoc object, which also inherits from Exception.

User-defined exception classes should inherit from Exception too, and define at least a method message.

class X::YourApp::SomeError is Exception {
        method message() {
            "A YourApp-Specific error occurred: out of coffee!";
        }
    }

Methods

method message

method message(Exception:D: --> Str:D)

This is a stub that must be overwritten by subclasses, and should return the exception message.

Special care should be taken that this method does not produce an exception itself.

try die "Something bad happened";
    if ($!) {
        say $!.message; # OUTPUT: «Something bad happened.␤»
    }

method backtrace

method backtrace(Exception:D:)

Returns the backtrace associated with the exception in a Backtrace object or an empty string if there is none. Only makes sense on exceptions that have been thrown at least once.

try die "Something bad happened";
    with $! { .backtrace.print ; }

method throw

method throw(Exception:D:)

Throws the exception.

my $exception = X::AdHoc.new;    # Totally fine
    try $exception.throw;            # Throws
    if ($!) { #`( some handling ) }; # Suppress the exception

method resume

method resume(Exception:D:)

Resumes control flow where .throw left it when handled in a CATCH block.

# For example, resume control flow for any exception
    CATCH { default { .resume } }

method rethrow

method rethrow(Exception:D:)

Rethrows an exception that has already been thrown at least once. This is different from throw in that it preserves the original backtrace.

sub f() { die 'Bad' };
    sub g() { f; CATCH { default { .rethrow } } };
    g;
    CATCH { default { say .backtrace.full } };

routine fail

multi  fail(Exception $e)
    method fail(Exception:D:)

Exits the calling Routine and returns a Failure object wrapping the exception.

# A custom exception defined
class ForbiddenWord is Exception {
    has Str $.word;
    method message { "This word is forbidden: «$!word»" }
}

sub say-word ( $word ) {
    ForbiddenWord.new(:word($word)).fail if $word eq 'foo';
    $word.say;
}

my $result = say-word("foo");
say $result.exception;

The routine form works in the same way, with an alternative syntax: fail ForbiddenWord.new(:word($word)).

method gist

multi method gist(Exception:D:)

Returns whatever the exception printer should produce for this exception. The default implementation returns message and backtrace separated by a newline.

my $e = X::AdHoc.new(payload => "This exception is pretty bad");
    try $e.throw;
    if ($!) { say $!.gist; };
    # OUTPUT: «This exception is pretty bad
    #   in block <unit> at <unknown file> line 1␤»

method Failure

method Failure(Exception:D: --> Failure:D)

Available as of the 2022.06 release of the Rakudo compiler.

Coerces the Exception into a Failure object.

routine die

multi  die()
    multi  die(*@message)
    multi  die(Exception:D $e)
    method die(Exception:D:)

Throws a fatal Exception. The default exception handler prints each element of the list to $*ERR (STDERR).

die "Important reason";

If the subroutine form is called without arguments, the value of $! variable is checked. If it is set to a .DEFINITE value, its value will be used as the Exception to throw if it's of type Exception, otherwise, it will be used as payload of X::AdHoc exception. If $! is not .DEFINITE, X::AdHoc with string "Died" as payload will be thrown.

die will print by default the line number where it happens

die "Dead";
# OUTPUT: «(exit code 1) Dead␤
# in block <unit> at /tmp/dead.raku line 1␤␤»

However, that default behavior is governed at the Exception level and thus can be changed to anything we want by capturing the exception using CATCH. This can be used, for instance, to suppress line numbers.

CATCH {
  default {
    .payload.say
  }
};
die "Dead" # OUTPUT: «Dead␤»

sub warn

multi warn(*@message)

Throws a resumable warning exception, which is considered a control exception, and hence is invisible to most normal exception handlers. The outermost control handler will print the warning to $*ERR. After printing the warning, the exception is resumed where it was thrown. To override this behavior, catch the exception in a CONTROL block. A quietly {...} block is the opposite of a try {...} block in that it will suppress any warnings but pass fatal exceptions through.

To simply print to $*ERR, please use note instead. warn should be reserved for use in threatening situations when you don't quite want to throw an exception.

warn "Warning message";

See Also

class Backtrace

Snapshot of the dynamic call stack

class Backtrace::Frame

Single frame of a Backtrace

role CX::Done

Done control exception

role CX::Emit

Emit control exception

role CX::Last

Last control exception

role CX::Next

Next control exception

role CX::Proceed

Proceed control exception

role CX::Redo

Redo control exception

role CX::Return

Return control exception

role CX::Succeed

Succeed control exception

role CX::Take

Take control exception

role CX::Warn

Control exception warning

class Failure

Delayed exception

class X::AdHoc

Error with a custom message

class X::Anon::Augment

Compilation error due to augmenting an anonymous package

class X::Anon::Multi

Compilation error due to declaring an anonymous multi

class X::Assignment::RO

Exception thrown when trying to assign to something read-only

class X::Attribute::NoPackage

Compilation error due to declaring an attribute outside of a package

class X::Attribute::Package

Compilation error due to declaring an attribute in an ineligible package

class X::Attribute::Required

Compilation error due to not declaring an attribute with the is required trait

class X::Attribute::Undeclared

Compilation error due to an undeclared attribute

class X::Augment::NoSuchType

Compilation error due to augmenting a non-existing type

class X::Bind

Error due to binding to something that is not a variable or container

class X::Bind::NativeType

Compilation error due to binding to a natively typed variable

class X::Bind::Slice

Error due to binding to a slice

class X::Caller::NotDynamic

Error while trying to access a non dynamic variable through CALLER

class X::Cannot::Empty

Error due to inappropriate usage of an empty collection

class X::Cannot::Lazy

Error due to inappropriate usage of a lazy list

class X::Channel::ReceiveOnClosed

Error due to calling receive on a closed channel

class X::Channel::SendOnClosed

Error due to calling send on a closed channel

class X::Composition::NotComposable

Compilation error due to composing an ineligible type

class X::Constructor::Positional

Error due to passing positional arguments to a default constructor

role X::Control

Role for control exceptions

class X::ControlFlow

Error due to calling a loop control command in an ineligible scope

class X::ControlFlow::Return

Error due to calling return outside a routine

class X::DateTime::TimezoneClash

Error due to using both time zone offset and :timezone

class X::Declaration::Scope

Compilation error due to a declaration with an ineligible scope

class X::Declaration::Scope::Multi

Compilation error due to declaring a multi with an ineligible scope

class X::Does::TypeObject

Error due to mixing into a type object

class X::Dynamic::NotFound

Runtime error thrown when a dynamic variable does not exist

class X::Eval::NoSuchLang

Error due to specifying an unknown language for EVAL

class X::Export::NameClash

Compilation error due to exporting the same symbol twice

class X::Inheritance::NotComposed

Error due to inheriting from a type that's not composed yet

class X::Inheritance::Unsupported

Compilation error due to inheriting from an ineligible type

class X::IO::BinaryMode

Error while invoking methods on a handle in binary mode.

class X::IO::Chdir

Error while trying to change the working directory

class X::IO::Chmod

Error while trying to change file permissions

class X::IO::Chown

Error while trying to change file ownership

class X::IO::Copy

Error while trying to copy a file

class X::IO::Cwd

Error while trying to determine the current working directory

class X::IO::Dir

Error while trying to get a directory's contents

class X::IO::DoesNotExist

Error while doing file tests on a non existing path

class X::IO::Link

Error while trying to create a link

class X::IO::Mkdir

Error while trying to create a directory

class X::IO::Move

Error while trying to move a file

class X::IO::Rename

Error while trying to rename a file or directory

class X::IO::Rmdir

Error while trying to remove a directory

class X::IO::Symlink

Error while trying to create a symbolic link

class X::IO::Unlink

Error while trying to remove a file

class X::Method::InvalidQualifier

Error due to calling a qualified method from an ineligible class

class X::Method::NotFound

Error due to calling a method that isn't there

class X::Method::Private::Permission

Compilation error due to calling a private method without permission

class X::Method::Private::Unqualified

Compilation error due to an unqualified private method call

class X::Mixin::NotComposable

Error due to using an ineligible type as a mixin

class X::NoDispatcher

Error due to calling a dispatch command in an ineligible scope

class X::Numeric::CannotConvert

Error while trying to coerce a number to another type

class X::Numeric::DivideByZero

Error while trying to divide by zero

class X::Numeric::Real

Error while trying to coerce a number to a Real type

class X::NYI

Error due to use of an unimplemented feature

class X::Obsolete

Compilation error due to use of obsolete syntax

class X::OutOfRange

Error due to indexing outside of an allowed range

class X::Package::Stubbed

Compilation error due to a stubbed package that is never defined

class X::Parameter::Default

Compilation error due to an unallowed default value in a signature

class X::Parameter::MultipleTypeConstraints

Compilation error due to a parameter with multiple type constraints

class X::Parameter::Placeholder

Compilation error due to an unallowed placeholder in a signature

class X::Parameter::Twigil

Compilation error due to an unallowed twigil in a signature

class X::Parameter::WrongOrder

Compilation error due to passing parameters in the wrong order

class X::Phaser::Multiple

Compilation error due to multiple phasers of the same type

class X::Phaser::PrePost

Error due to a false return value of a PRE/POST phaser

class X::Placeholder::Block

Compilation error due to a placeholder in an ineligible block

class X::Placeholder::Mainline

Compilation error due to a placeholder in the mainline

class X::Proc::Async::AlreadyStarted

Error due to calling start on an already started Proc::Async object

class X::Proc::Async::BindOrUse

Error due to trying to bind a handle that is also used

class X::Proc::Async::CharsOrBytes

Error due to tapping the same Proc::Async stream for both text and binary reading

class X::Proc::Async::MustBeStarted

Error due to interacting with a Proc::Async stream before spawning its process

class X::Proc::Async::OpenForWriting

Error due to writing to a read-only Proc::Async object

class X::Proc::Async::TapBeforeSpawn

Error due to tapping a Proc::Async stream after spawning its process

class X::Proc::Unsuccessful

Exception thrown if a Proc object is sunk after the process it ran exited unsuccessfully

class X::Promise::CauseOnlyValidOnBroken

Error due to asking why an unbroken promise has been broken.

class X::Promise::Vowed

Error due to directly trying to keep/break a vowed promise.

class X::Redeclaration

Compilation error due to declaring an already declared symbol

class X::Role::Initialization

Error due to passing an initialization value to an ineligible role

class X::Scheduler::CueInNaNSeconds

Error caused by passing NaN to Scheduler.cue as :at, :in, or :every

class X::Seq::Consumed

Error due to trying to reuse a consumed sequence

class X::Sequence::Deduction

Error due to constructing a sequence from ineligible input

class X::Signature::NameClash

Compilation error due to two named parameters with the same name

class X::Signature::Placeholder

Compilation error due to placeholders in a block with a signature

class X::Str::Match::x

Invalid argument type for :x argument to Str matching methods

class X::Str::Numeric

Error while trying to coerce a string to a number

class X::StubCode

Runtime error due to execution of stub code

class X::Syntax::Augment::WithoutMonkeyTyping

Compilation error due to augmenting a type without the MONKEY-TYPING pragma

class X::Syntax::Comment::Embedded

Compilation error due to a malformed inline comment

class X::Syntax::Confused

Compilation error due to unrecognized syntax

class X::Syntax::InfixInTermPosition

Compilation error due to an infix in term position

class X::Syntax::Malformed

Compilation error due to a malformed construct (usually a declarator)

class X::Syntax::Missing

Compilation error due to a missing piece of syntax

class X::Syntax::NegatedPair

Compilation error due to passing an argument to a negated colonpair

class X::Syntax::NoSelf

Compilation error due to implicitly using a self that is not there

class X::Syntax::Number::RadixOutOfRange

Compilation error due to an unallowed radix in a number literal

class X::Syntax::P5

Compilation error due to use of Perl-only syntax

class X::Syntax::Perl5Var

Compilation error due to use of Perl-only default variables

class X::Syntax::Regex::Adverb

Compilation error due to an unrecognized regex adverb

class X::Syntax::Regex::SolitaryQuantifier

Compilation error due to a regex quantifier without preceding atom

class X::Syntax::Reserved

Compilation error due to use of syntax reserved for future use

class X::Syntax::Self::WithoutObject

Compilation error due to invoking self in an ineligible scope

class X::Syntax::Signature::InvocantMarker

Compilation error due to a misplaced invocant marker in a signature

class X::Syntax::Term::MissingInitializer

Compilation error due to declaring a term without initialization

class X::Syntax::UnlessElse

Compilation error due to an unless clause followed by else

class X::Syntax::Variable::Match

Compilation error due to declaring a match variable

class X::Syntax::Variable::Numeric

Compilation error due to declaring a numeric symbol

class X::Syntax::Variable::Twigil

Compilation error due to an unallowed twigil in a declaration

class X::Temporal::InvalidFormat

Error due to using an invalid format when creating a DateTime or Date

class X::TypeCheck

Error due to a failed type check

class X::TypeCheck::Assignment

Error due to a failed type check during assignment

class X::TypeCheck::Binding

Error due to a failed type check during binding

class X::TypeCheck::Return

Error due to a failed typecheck during return

class X::TypeCheck::Splice

Compilation error due to a macro trying to splice a non-AST value

class X::Undeclared

Compilation error due to an undeclared symbol

The Camelia image is copyright 2009 by Larry Wall. "Raku" is trademark of the Yet Another Society. All rights reserved.