Exceptions: Difference between revisions

m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(8 intermediate revisions by 5 users not shown)
Line 4:
{{omit from|M4}}
{{omit from|Retro}}
[[Category:Flow control]]
 
This task is to give an example of an exception handling routine
Line 20 ⟶ 21:
 
X.try
X.throw SillyError(‘egg’)
X.catch SillyError se
print(se.message)</syntaxhighlight>
Line 1,596 ⟶ 1,597:
A catch causes all the statements preceding it within a block to be the implicit try block.
 
<syntaxhighlight lang="langur"># do something
Exceptions in langur are hashes guaranteed to contain certain fields, even if they're empty.
 
<syntaxhighlight lang="langur"># do something
throw "not a math exception"
 
catch .[e] {
if .e["'cat"] == "math" {
# change result...
} else {
Line 1,610 ⟶ 1,609:
} else {
# no exception
};
...
}</syntaxhighlight>
 
An else section on a catch is optional. As of 0.7, youYou can also use else if on a catch.
 
=== exception variable ===
An exception variable may be specified, or you can simply use the implicit variable, which is _err. Prior to 0.7, the implicit exception variable was .err.
 
<syntaxhighlight lang="langur">100 / 0
100 / 0
 
catch {
if _err["'cat"] == "math" {
# change result
123
} else {
# rethrow the exception
throw
}
}
}</syntaxhighlight>
 
<syntaxhighlight lang="langur">val .safediv = f { .x / .y ; catch { 0 } }
.val safediv = fn(7x, 7y) #{ x / y ; catch : 0 1}
.safediv(7, 07) # 0</syntaxhighlight>1
safediv(7, 0) # 0
</syntaxhighlight>
 
=={{header|Lasso}}==
Line 2,260 ⟶ 2,264:
=={{header|Pascal}}==
See [[Exceptions#Delphi | Delphi]]
 
=={{header|PascalABC.NET}}==
 
User defined exceptuin class
<syntaxhighlight lang="delphi">
type MyException = class(Exception) end;
</syntaxhighlight>
 
Throw an exception
<syntaxhighlight lang="delphi">
raise new MyException;
</syntaxhighlight>
 
Catch an exception
<syntaxhighlight lang="delphi">
try
...
except
on e: MyException do
statement
end;
</syntaxhighlight>
 
=={{header|Perl}}==
Line 3,094 ⟶ 3,120:
An exception is thrown by the ''die'' keyword, which, if not caught, it terminates the program with an appropriate exit code.
<syntaxhighlight lang="ruby">try {
die "I'm dead!"; # throws an exception of type 'error'
}
catch { |type, msg|
say "msg: #{msg}"; # msg: I'm dead! at test.sf line 2.
}
catch { |type, msg|
say "type: #{type}"; # type: error
say "msg: #{msg}"; # msg: I'm dead! at test.sf line 2.
};
 
say "I'm alive...";
die "Now I'm dead!"; # this line terminates the program
say "Or am I?"; # Yes, you are!</syntaxhighlight>
{{out}}
<pre>
Line 3,109 ⟶ 3,134:
msg: I'm dead! at test.sf line 2.
I'm alive...
Now I'm dead! at test.sf line 109.
</pre>
 
1,007

edits