SlideShare uma empresa Scribd logo
1 de 13
Exceptions

   Lightning Talk on Exceptions
   MiltonKeynes.pm 12-Jan-2009
   Peter Edwards
    peter@dragonstaff.co.uk




   Slides at http://perl.dragonstaff.co.uk
What Are Exceptions

   Defensive programming
       expected behaviour
       you should anticipate bugs or incorrect input
       recovery from
        or reporting of
        "exceptions" to expected behaviour
Exception Handling

   detect
       check data and die/throw exception when invalid
       wrap calls in eval:
          eval { $foo->bah() };
          die "foo failed: $@" if $@;
   classify
       user error
        program error
       severity level (debug, info, warn, error, fatal)
Exception Handling

   report
       warn to STDERR and continue
       die with message to STDOUT
       print to screen
       logging with log4perl - severity level
Exception Methods

   Return codes
       don't do this!
       is it 0 or 1 or a special value that is failure?
       system calls vary
       easy to forget to check return code in caller leading
        to hidden error
       difficult to return code and message
            sub a { return (1, "Invalid file format, file path: $fpath"); }
            my $rc = a(); # oops, only gets message not code
Exception Methods
   hierarchy of die/rethrow inside eval
       sub a {
           die "oops"; # should be a croak() for context
           return 1;
        }
        sub b {
           my $rc;
           eval { $rc = a() }; # undef
           die "a() failed: $@" if $@; # rethrow
           return $rc;
        }
        eval { print "b returns " . b() };
        print "b() failed: $@" if $@;
        >>> b() failed: a() failed: oops at t.pl line 2.
Better Exceptions

   eval/die/rethrow is a bit clunky
   built-in error object methods would be nice
   languages like java or javascript give you
    try... catch... throw
   so use a CPAN exception module... which one?
Modules available

   Fatal - makes failed builtins throw exceptions
       use Fatal qw( open close );

   Error
       gives you try... catch... throw
       obscure nested closure memory leak
Modules available

   Class::Throwable
       lightweight
       easy to use
       controllable levels of verbosity
       extensible exception objects
       I use this one
Modules Available

   Exception::Class
       full-powered
       complex
       may be a performance overhead
Modules Available

   Others include: Exception

   Good discussion of pros/cons in
    Class::Throwable perldoc
Gotcha

   DIE blocks can reset $@
       sub check {
           croak ”invalid parameter” unless $_[0];
        }
        sub DESTROY {
           local $@; # forget me and you've had it
           eval { somefoo() };
           print ”in DESTROYn”;
        }
        eval { check(undef) };
        print ”$@n”;
        >>> (empty)
   CPAN solution: Devel::EvalError
Perl Best Practices

   ”Perl Best Practices” pp.273-296 first ed. 2005,
    D.Conway pub. O'Reilly
       Ten essential development practices
        #8 Throw exceptions instead of returning special
        values or setting flags
   See also Summary of Chapter 13, Error
    Handling (too many points to list here!)
   -end-

Mais conteúdo relacionado

Mais procurados

Exception handling and templates
Exception handling and templatesException handling and templates
Exception handling and templates
farhan amjad
 
Lecture 2 php basics (1)
Lecture 2  php basics (1)Lecture 2  php basics (1)
Lecture 2 php basics (1)
Core Lee
 
Exception handling chapter15
Exception handling chapter15Exception handling chapter15
Exception handling chapter15
Kumar
 
1584503386 1st chap
1584503386 1st chap1584503386 1st chap
1584503386 1st chap
thuhiendtk4
 

Mais procurados (20)

Introduction to php exception and error management
Introduction to php  exception and error managementIntroduction to php  exception and error management
Introduction to php exception and error management
 
Handling error & exception in php
Handling error & exception in phpHandling error & exception in php
Handling error & exception in php
 
Error reporting in php
Error reporting in php Error reporting in php
Error reporting in php
 
Web Application Development using PHP Chapter 2
Web Application Development using PHP Chapter 2Web Application Development using PHP Chapter 2
Web Application Development using PHP Chapter 2
 
Advanced php
Advanced phpAdvanced php
Advanced php
 
PerlScripting
PerlScriptingPerlScripting
PerlScripting
 
null Pune meet - Application Security: Code injection
null Pune meet - Application Security: Code injectionnull Pune meet - Application Security: Code injection
null Pune meet - Application Security: Code injection
 
Surprise! It's PHP :) (unabridged)
Surprise! It's PHP :) (unabridged)Surprise! It's PHP :) (unabridged)
Surprise! It's PHP :) (unabridged)
 
Exception handling and templates
Exception handling and templatesException handling and templates
Exception handling and templates
 
Exception Handling in the C++ Constructor
Exception Handling in the C++ ConstructorException Handling in the C++ Constructor
Exception Handling in the C++ Constructor
 
Wtf per lineofcode
Wtf per lineofcodeWtf per lineofcode
Wtf per lineofcode
 
Introduction to writing readable and maintainable Perl
Introduction to writing readable and maintainable PerlIntroduction to writing readable and maintainable Perl
Introduction to writing readable and maintainable Perl
 
Lecture 2 php basics (1)
Lecture 2  php basics (1)Lecture 2  php basics (1)
Lecture 2 php basics (1)
 
Exception handling in c++
Exception handling in c++Exception handling in c++
Exception handling in c++
 
C Tutorials
C TutorialsC Tutorials
C Tutorials
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling chapter15
Exception handling chapter15Exception handling chapter15
Exception handling chapter15
 
1584503386 1st chap
1584503386 1st chap1584503386 1st chap
1584503386 1st chap
 
Test doubles
Test doublesTest doubles
Test doubles
 
Conditional Statement in C Language
Conditional Statement in C LanguageConditional Statement in C Language
Conditional Statement in C Language
 

Destaque

Manual de base de datos
Manual de base de datosManual de base de datos
Manual de base de datos
gime96
 
Base de datos gimenez tavella
Base de datos gimenez  tavellaBase de datos gimenez  tavella
Base de datos gimenez tavella
gime96
 
Apresentação teleconferência de resultados 2 t10
Apresentação   teleconferência de resultados 2 t10Apresentação   teleconferência de resultados 2 t10
Apresentação teleconferência de resultados 2 t10
Braskem_RI
 
Basededatos.pdf
Basededatos.pdfBasededatos.pdf
Basededatos.pdf
gime96
 
Base de datos gimenez tavella
Base de datos gimenez  tavellaBase de datos gimenez  tavella
Base de datos gimenez tavella
gime96
 
Microchip
MicrochipMicrochip
Microchip
gime96
 
ใบงานสำรวจตนเอง M
ใบงานสำรวจตนเอง Mใบงานสำรวจตนเอง M
ใบงานสำรวจตนเอง M
Fiction Lee'jslism
 

Destaque (9)

Manual de base de datos
Manual de base de datosManual de base de datos
Manual de base de datos
 
Guia 11
Guia 11Guia 11
Guia 11
 
Base de datos gimenez tavella
Base de datos gimenez  tavellaBase de datos gimenez  tavella
Base de datos gimenez tavella
 
Apresentação teleconferência de resultados 2 t10
Apresentação   teleconferência de resultados 2 t10Apresentação   teleconferência de resultados 2 t10
Apresentação teleconferência de resultados 2 t10
 
ขนมจ็อก
ขนมจ็อกขนมจ็อก
ขนมจ็อก
 
Basededatos.pdf
Basededatos.pdfBasededatos.pdf
Basededatos.pdf
 
Base de datos gimenez tavella
Base de datos gimenez  tavellaBase de datos gimenez  tavella
Base de datos gimenez tavella
 
Microchip
MicrochipMicrochip
Microchip
 
ใบงานสำรวจตนเอง M
ใบงานสำรวจตนเอง Mใบงานสำรวจตนเอง M
ใบงานสำรวจตนเอง M
 

Semelhante a Perl exceptions lightning talk

Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
Kang-min Liu
 
Exception Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in RubyException Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in Ruby
Wen-Tien Chang
 
Perl Intro 7 Subroutines
Perl Intro 7 SubroutinesPerl Intro 7 Subroutines
Perl Intro 7 Subroutines
Shaun Griffith
 
Yapcasia2011 - Hello Embed Perl
Yapcasia2011 - Hello Embed PerlYapcasia2011 - Hello Embed Perl
Yapcasia2011 - Hello Embed Perl
Hideaki Ohno
 

Semelhante a Perl exceptions lightning talk (20)

Getting testy with Perl
Getting testy with PerlGetting testy with Perl
Getting testy with Perl
 
Perl Intro 4 Debugger
Perl Intro 4 DebuggerPerl Intro 4 Debugger
Perl Intro 4 Debugger
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
Perl_Part5
Perl_Part5Perl_Part5
Perl_Part5
 
Handling Exceptions In C & C++[Part A]
Handling Exceptions In C & C++[Part A]Handling Exceptions In C & C++[Part A]
Handling Exceptions In C & C++[Part A]
 
Red Flags in Programming
Red Flags in ProgrammingRed Flags in Programming
Red Flags in Programming
 
Introduction to Writing Readable and Maintainable Perl (YAPC::EU 2011 Version)
Introduction to Writing Readable and Maintainable Perl (YAPC::EU 2011 Version)Introduction to Writing Readable and Maintainable Perl (YAPC::EU 2011 Version)
Introduction to Writing Readable and Maintainable Perl (YAPC::EU 2011 Version)
 
Getting modern with logging via log4perl
Getting modern with logging via log4perlGetting modern with logging via log4perl
Getting modern with logging via log4perl
 
Exception Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in RubyException Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in Ruby
 
A exception ekon16
A exception ekon16A exception ekon16
A exception ekon16
 
Php Chapter 1 Training
Php Chapter 1 TrainingPhp Chapter 1 Training
Php Chapter 1 Training
 
Python Programming Essentials - M21 - Exception Handling
Python Programming Essentials - M21 - Exception HandlingPython Programming Essentials - M21 - Exception Handling
Python Programming Essentials - M21 - Exception Handling
 
Perl Intro 7 Subroutines
Perl Intro 7 SubroutinesPerl Intro 7 Subroutines
Perl Intro 7 Subroutines
 
Yapcasia2011 - Hello Embed Perl
Yapcasia2011 - Hello Embed PerlYapcasia2011 - Hello Embed Perl
Yapcasia2011 - Hello Embed Perl
 
Code Fast, die() Early, Throw Structured Exceptions
Code Fast, die() Early, Throw Structured ExceptionsCode Fast, die() Early, Throw Structured Exceptions
Code Fast, die() Early, Throw Structured Exceptions
 
Exception Handling - The Good, the Bad and the Maybe (APEXCONN23)
Exception Handling - The Good, the Bad and the Maybe (APEXCONN23)Exception Handling - The Good, the Bad and the Maybe (APEXCONN23)
Exception Handling - The Good, the Bad and the Maybe (APEXCONN23)
 
ppt7
ppt7ppt7
ppt7
 
ppt2
ppt2ppt2
ppt2
 
name name2 n
name name2 nname name2 n
name name2 n
 

Mais de Peter Edwards (8)

Enhancing engagement through content
Enhancing engagement through contentEnhancing engagement through content
Enhancing engagement through content
 
Twitter oauth
Twitter oauthTwitter oauth
Twitter oauth
 
BBC World Service Twitter OAuth Perl
BBC World Service Twitter OAuth PerlBBC World Service Twitter OAuth Perl
BBC World Service Twitter OAuth Perl
 
Role based access control
Role based access controlRole based access control
Role based access control
 
Getting started with Catalyst and extjs
Getting started with Catalyst and extjsGetting started with Catalyst and extjs
Getting started with Catalyst and extjs
 
Desperately seeking a lightweight Perl framework
Desperately seeking a lightweight Perl frameworkDesperately seeking a lightweight Perl framework
Desperately seeking a lightweight Perl framework
 
Real world cross-platform testing
Real world cross-platform testingReal world cross-platform testing
Real world cross-platform testing
 
Open Source for Government - PSEICT Conference - British Council Case Study u...
Open Source for Government - PSEICT Conference - British Council Case Study u...Open Source for Government - PSEICT Conference - British Council Case Study u...
Open Source for Government - PSEICT Conference - British Council Case Study u...
 

Último

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Último (20)

Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 

Perl exceptions lightning talk

  • 1. Exceptions  Lightning Talk on Exceptions  MiltonKeynes.pm 12-Jan-2009  Peter Edwards peter@dragonstaff.co.uk  Slides at http://perl.dragonstaff.co.uk
  • 2. What Are Exceptions  Defensive programming  expected behaviour  you should anticipate bugs or incorrect input  recovery from or reporting of "exceptions" to expected behaviour
  • 3. Exception Handling  detect  check data and die/throw exception when invalid  wrap calls in eval: eval { $foo->bah() }; die "foo failed: $@" if $@;  classify  user error program error  severity level (debug, info, warn, error, fatal)
  • 4. Exception Handling  report  warn to STDERR and continue  die with message to STDOUT  print to screen  logging with log4perl - severity level
  • 5. Exception Methods  Return codes  don't do this!  is it 0 or 1 or a special value that is failure?  system calls vary  easy to forget to check return code in caller leading to hidden error  difficult to return code and message  sub a { return (1, "Invalid file format, file path: $fpath"); }  my $rc = a(); # oops, only gets message not code
  • 6. Exception Methods  hierarchy of die/rethrow inside eval  sub a { die "oops"; # should be a croak() for context return 1; } sub b { my $rc; eval { $rc = a() }; # undef die "a() failed: $@" if $@; # rethrow return $rc; } eval { print "b returns " . b() }; print "b() failed: $@" if $@; >>> b() failed: a() failed: oops at t.pl line 2.
  • 7. Better Exceptions  eval/die/rethrow is a bit clunky  built-in error object methods would be nice  languages like java or javascript give you try... catch... throw  so use a CPAN exception module... which one?
  • 8. Modules available  Fatal - makes failed builtins throw exceptions  use Fatal qw( open close );  Error  gives you try... catch... throw  obscure nested closure memory leak
  • 9. Modules available  Class::Throwable  lightweight  easy to use  controllable levels of verbosity  extensible exception objects  I use this one
  • 10. Modules Available  Exception::Class  full-powered  complex  may be a performance overhead
  • 11. Modules Available  Others include: Exception  Good discussion of pros/cons in Class::Throwable perldoc
  • 12. Gotcha  DIE blocks can reset $@  sub check { croak ”invalid parameter” unless $_[0]; } sub DESTROY { local $@; # forget me and you've had it eval { somefoo() }; print ”in DESTROYn”; } eval { check(undef) }; print ”$@n”; >>> (empty)  CPAN solution: Devel::EvalError
  • 13. Perl Best Practices  ”Perl Best Practices” pp.273-296 first ed. 2005, D.Conway pub. O'Reilly  Ten essential development practices #8 Throw exceptions instead of returning special values or setting flags  See also Summary of Chapter 13, Error Handling (too many points to list here!)  -end-