Perlで例外

30分プログラム、その428。Exception::Class - A module that allows you to declare real exception classes in Perl - metacpan.orgを使うとPerlでも例外が使えるらしいので試してみる。

使い方

# try
eval{
  # throw	
  InvalidArgument->throw("some_message");
};

# catch
if(my $e = Exception::Class->caught('InvalidArgument')){
  ...
}

ソースコード

#! /usr/bin/perl
# -*- mode:perl; coding:utf-8 -*-
#
# exception.pl -
#
# Copyright(C) 2008 by mzp
# Author: MIZUNO Hiroki / mzpppp at gmail dot com
# http://howdyworld.org
#
# Timestamp: 2008/12/02 22:16:38
#
# This program is free software; you can redistribute it and/or
# modify it under MIT Lincence.
#

use strict;
use warnings;
use Exception::Class qw(InvalidArgument);

sub fact($){
    my ($n) = @_;
    if($n < 0){
	InvalidArgument->throw("n should be positive");
    }elsif($n == 0){
	1;
    }else{
	$n * &fact($n-1);
    }
}

eval{
    my $n = fact(-1);
    print "fact(-1)$n\n";
};

if(my $e = Exception::Class->caught('InvalidArgument')){
    print "catch exception\n";
}
**参考
- [http://d.hatena.ne.jp/mzp/19000101/list:title=過去の30分プログラム]