1. Perl
  2. builtin functions
  3. here

die function - display an error message and exit the program

Use the die function to display a error message and exit the program . The line number where the program ended is automatically added to the end of the message. To hide the line number, end it with a line break.

# Display an error message and exit the program

# With line number
die $message;

# No line number
die "$message\n";

This is an example that displays the usage and terminates the program when the argument does not exist. $0 is the script name.

# Exit the program if the argument does not exist
my $file = shift;
die "Usage: $0[file]" unless $file;

This is an example to terminate the program when the file open fails.

# Quit the program if file open fails
my $file = 'a.txt';
open my $fh, '<', $file
  or die "Can't open file \" $file\":$!";

The exit status is 0 if the program exits successfully. If you exit the program with die, the exit status will be a non-zero value. The exit status of die is determined by the following rules.

1. The value of $! Evaluated numerically. (Error notified by OS)
2. If $! Is 0 ($? >> 8). (Exit status of child process)
3. 255 if ($? >> 8) is 0

Exception handling

Languages such as Java provide a mechanism called exceptions. Perl provides a concise exception handling mechanism that uses die and eval blocks.

Use die to throw an exception. Use "eval {}" to catch the exception. Use $@to determine if an exception has occurred. If an exception occurs, an error message will be set in $@.

# Exception handling flow
eval {
  # Processing that terminates programs that use die

if ($@) {
  # Exception handling

A simple example of exception handling.

# Exception handling
my $num;
eval {
  die "Number is undefined." unless defined $num;

if ($@) {
  die "Catch and throw again $@";

See below for a detailed explanation of Perl's exception handling.

Related Informatrion