PE

Perl Error Handling

Perl error handling using die/eval, Carp, and exception class modules

Details

Language / Topic
perlPerl
Category
Error Handling

Rules

balanced
- Use `eval { ... }; if ($@) { ... }` to catch exceptions — always localize `$@` with `local $@` before calling code that might reset it.
- Use `Carp::croak` in modules to report errors at the caller's location — use `Carp::confess` when a full stack trace is needed.
- Always check return values from system calls (`open`, `sysread`, `connect`) and die with `$!` or `$@` on failure.
- Use `Exception::Class` or `Throwable` (Moo-based) to define typed exception hierarchies — catch by class with `$e->isa('MyException')`.
- Use `Try::Tiny` or `Feature::Compat::Try` (for Perl 5.36+ `try/catch`) to avoid `$@` clobbering issues in nested eval blocks.
- Always end `die` messages with `\n` to suppress Perl's automatic ` at file line N` suffix when the error is user-facing.
- Use `local $SIG{__DIE__}` carefully — prefer `eval` blocks over global die handlers for localized error handling.