WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Perl · Advanced · question 53 of 100

Explain how to create and use a custom exception class in Perl to handle application-specific errors.?

📕 Buy this interview preparation book: 100 Perl questions & answers — PDF + EPUB for $5

In Perl, an exception is an error or an unexpected event that occurs during run-time. Exceptions are used to handle exceptions or fatal errors that are not possible to handle at compile-time. Perl provides some built-in exceptions which can be thrown by using the ‘die‘ function. However, it is possible to create a custom exception class to handle application-specific errors.

To create a custom exception class, you need to use the ‘Exception::Class‘ module, which can be installed from CPAN. Once installed, you can create a new exception class as follows:

use Exception::Class (
    'MyException' => {
        fields => ['details'],
    },
);

In the above code, we are creating a new exception class called ‘MyException‘ that will have an additional field called ‘details‘. You can add as many fields as you need to provide more information about the exception.

Once the custom exception class is defined, you can throw an exception by instantiating an object of that class and throwing it using the ‘throw‘ method. For example:

sub do_something {
    # ...
    if ($error) {
        MyException->throw( details => "Something went wrong!" );
    }
    # ...
}

In the above code, we are throwing a new ‘MyException‘ object with the ‘details‘ field set to "Something went wrong!". This exception can then be caught and handled in a catch block as follows:

eval {
    do_something();
};

if ( my $e = Exception::Class->caught('MyException') ) {
    # handle the exception
    print "Error: ", $e->details, "n";
}
elsif ($@) {
    # handle other exceptions
    # ...
}

In the above code, we are using the ‘eval‘ block to execute the ‘do_something‘ function. If an exception occurs, we catch it using the ‘Exception::Class->caught‘ method. If the exception is of type ‘MyException‘, we handle it by printing the details field. You can add more catch blocks to handle different types of exceptions.

Overall, using a custom exception class allows you to create more descriptive and specific error messages that can be easily caught and handled in your code.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Perl interview — then scores it.
📞 Practice Perl — free 15 min
📕 Buy this interview preparation book: 100 Perl questions & answers — PDF + EPUB for $5

All 100 Perl questions · All topics