SlideShare una empresa de 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-

Más contenido relacionado

La actualidad más candente

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
 

La actualidad más candente (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
 

Destacado

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
 

Destacado (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
 

Similar 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
 

Similar 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
 

Más 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
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Último (20)

CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
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
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
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
 
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
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
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
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 

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-