This commit is contained in:
Ingy döt Net 2013-10-27 22:24:23 +00:00
parent 6f050a029e
commit 776bba907c
3887 changed files with 59894 additions and 7280 deletions

View file

@ -0,0 +1,25 @@
void
throwing(void)
{
o_text("throwing...\n");
error("now!");
}
void
catching(void)
{
o_text("ready to catch\n");
if (trap(throwing)) {
o_text("caught!\n");
} else {
# nothing was thrown
}
}
integer
main(void)
{
catching();
return 0;
}

View file

@ -0,0 +1,39 @@
void
ft(integer a, text &s)
{
if (a & 1) {
s = "odd";
error("bad number");
} elif (a & a - 1) {
s = "not a power of two";
error("bad number");
}
}
void
fc(integer a)
{
text e;
if (trap(ft, a, e)) {
v_text("exception of type `");
v_text(e);
v_text("' thrown for ");
v_integer(a);
v_newline();
} else {
v_text("no exception thrown for ");
v_integer(a);
v_newline();
}
}
integer
main(void)
{
fc(5);
fc(6);
fc(8);
return 0;
}

View file

@ -0,0 +1,12 @@
-module( exceptions ).
-export( [task/0] ).
task() ->
try
erlang:throw( new_exception )
catch
_:Exception -> io:fwrite( "Catched ~p~n", [Exception] )
end.

View file

@ -0,0 +1,23 @@
:- object(exceptions).
:- public(double/2).
double(X, Y) :-
catch(double_it(X,Y), Error, handler(Error, Y)).
handler(error(not_a_number(X), logtalk(This::double(X,Y), Sender)), Y) :-
% try to fix the error and resume computation;
% if not possible, rethrow the exception
( catch(number_codes(Nx, X), _, fail) ->
double_it(Nx, Y)
; throw(error(not_a_number(X), logtalk(This::double(X,Y), Sender)))
).
double_it(X, Y) :-
( number(X) ->
Y is 2*X
; this(This),
sender(Sender),
throw(error(not_a_number(X), logtalk(This::double(X,Y), Sender)))
).
:- end_object.

View file

@ -0,0 +1,10 @@
| ?- exceptions::double(1, Double).
Double = 2
yes
| ?- exceptions::double("1", Double).
Double = 2
yes
| ?- exceptions::double(a, Double).
uncaught exception: error(not_a_number(a),logtalk(exceptions::double(a,_),user))

View file

@ -0,0 +1,23 @@
// define a new exception
class MyException : Exception
{
...
}
// throw an exception
Foo() : void
{
throw MyException();
}
// catching exceptions
try {
Foo();
}
catch { // catch block uses pattern matching syntax
|e is MyException => ... // handle exception
|_ => throw e // rethrow unhandled exception
}
finally {
... // code executes whether or not exception was thrown
}