1. Perl
  2. here

Let's understand how Perl exception handling works

Perl allows you to use exception handling for error notification. Exception handling is very easy. All you have to do is learn how to raise an exception and how to catch it.

Raise an exception

Use the die function to raise an exception. When die is executed, the program will exit with an error status. You can pass a string to die.

# Raise an exception
die $message;

Let's write an example that raises an exception. I am trying to raise an exception if the value is not a positive integer in the function. The program will display a message and exit.

# Check value. Since it is not a positive integer, an exception will be thrown and the program will exit.
is_int('a');

sub is_int {
  my $num = shift;
  
  # Throw an exception if the value is not a positive integer
  die "\" $num\"must be number" unless $num =~ /^\d+$/;
}

Catch exceptions

You can catch an exception if you don't want the program to terminate when the called function raises an exception. Use eval block to catch the exception.

eval {Handling that raises an exception};

When an exception occurs, the message specified by the die function is stored in a predefined variable called $@. Write the processing when an exception occurs using this $@.

if ($@) {
    # What to do if an exception occurs
}

If an exception occurs, it means that an error has occurred, so in most cases it will not work if you continue processing. The motivation to catch the exception is when there is a possibility of recovering from the error by retrying (in the case of timeout etc.), or when the program ends as it is, garbage such as temporary files will remain, so post-processing is necessary. For example, the case.

This is an example to catch the exception that occurred in the is_int function.

# Catch exceptions
eval {is_int('a')};

# What to do if an exception occurs
if ($@) {
  print "Exception occur: $@";
}

sub is_int {
  my $num = shift;
  
  # Throw an exception if the value is not a positive integer
  die "\" $num\"must be number." unless $num =~ /^\d+$/;
}

When raising an exception in a module

If you want to create a module and raise an exception in the function in it, use the croak function of the Carp module. croak calls die internally. The difference from die is that croak includes the calling line number in the exception message. This allows the user of the module to know where the function or method was called.

package Your Module;

use Carp 'croak';

sub func {
  
  # Raise an exception
  croak "Error message";
}

Related Informatrion