Exception handling syntax: Difference between revisions

Content deleted Content added
m Reverted 2 edits by Sipraj (talk) to last revision by Serols
Perl 5: going through examples on this page, most of them seem to be done in-scope, yet here is an unsourced complaint about taking things out of scope; use case should be demonstrated and all langs treated accordingly
Line 744:
=== Perl 5===
{{Further information|Perl}}
The [[Perl]] mechanism for exception handling uses {{Perl2|die}} to throw an exception when wrapped inside an {{Perl2|eval { ... };}} block. After the {{Perl2|eval}}, the special variable {{Perl2|$@}} contains the value passed from {{Perl2|die}}. However, scoping issues can make doing this correctly quite ugly:
 
<syntaxhighlight lang="perl">
my ($error, $failed);
{
local $@;
$failed = not eval {
# Code that could throw an exception (using 'die')
open(FILE, $file) || die "Could not open file: $!";
while (<FILE>) {
process_line($_);
}
close(FILE) || die "Could not close $file: $!";
return 1;
};
$error = $@;
}
 
if ($failed) {
warn "got error: $error";
}
</syntaxhighlight>
 
Perl 5.005 added the ability to throw objects as well as strings. This allows better introspection and handling of types of exceptions.