This commit is contained in:
Ingy döt Net 2013-04-10 16:57:12 -07:00
parent 518da4a923
commit 764da6cbbb
6144 changed files with 83610 additions and 11 deletions

View file

@ -0,0 +1,4 @@
{{Control Structures}}
This task is to give an example of an exception handling routine and to "throw" a new exception.
Cf. [[Exceptions Through Nested Calls]]

View file

@ -0,0 +1,2 @@
---
note: Control Structures

View file

@ -0,0 +1,6 @@
# a user defined object #
MODE OBJECTFOO = STRUCT ( PROC (REF OBJECTFOO)BOOL foo event mended, ... );
PROC on foo event = (REF OBJECTFOO foo, PROC (REF OBJECTFOO)BOOL foo event)VOID: (
foo event mended OF foo := foo event
);

View file

@ -0,0 +1,8 @@
OBJECTFOO foo proxy := foo base; # event routines are specific to an foo #
on foo event(foo proxy, raise foo event);
WHILE TRUE DO
# now raise example foo event #
IF NOT (foo event mended OF foo proxy)(foo proxy) THEN undefined # trace back # FI
OD;

View file

@ -0,0 +1,5 @@
...
except foo event:
IF ... THEN # Alas, cannot handle it here continue propagation of #
IF NOT (foo event mended OF foo base)(foo base) THEN undefined # trace back # FI
FI

View file

@ -0,0 +1,7 @@
PROC raise foo event(REF OBJECTFOO foo)BOOL:
IF mend foo(foo) THEN
TRUE # continue #
ELSE
except foo event
FALSE # OR fall back to default event routine #
FI

View file

@ -0,0 +1 @@
Foo_Error : exception;

View file

@ -0,0 +1,4 @@
procedure Foo is
begin
raise Foo_Error;
end Foo;

View file

@ -0,0 +1,6 @@
...
exception
when Foo_Error =>
if ... then -- Alas, cannot handle it here,
raise; -- continue propagation of
end if;

View file

@ -0,0 +1,9 @@
procedure Call_Foo is
begin
Foo;
exception
when Foo_Error =>
... -- do something
when others =>
... -- this catches all other exceptions
end Call_Foo;

View file

@ -0,0 +1,12 @@
with Ada.Exceptions; use Ada.Exceptions;
with Ada.Text_IO; use Ada.Text_IO;
procedure Main is
begin
...
Raise_Exception (Foo_Error'Identity, "This is the exception message");
..
exception
when Error : others =>
Put_Line ("Something is wrong here" & Exception_Information (Error));
end Main;

View file

@ -0,0 +1,6 @@
try {
var lines = readfile ("input.txt")
process (lines)
} catch (e) {
do_somthing(e)
}

View file

@ -0,0 +1,7 @@
if (error) {
throw "Error"
}
if (something) {
throw new MyException (errorcode, a, b)
}

View file

@ -0,0 +1,4 @@
try
set num to 1 / 0
--do something that might throw an error
end try

View file

@ -0,0 +1,7 @@
try
set num to 1 / 0
--do something that might throw an error
on error errMess number errNum
--errMess and number errNum are optional
display alert "Error # " & errNum & return & errMess
end try

View file

@ -0,0 +1 @@
error "Error message." number 2000

View file

@ -0,0 +1,8 @@
try
BadlyCodedFunc()
catch e
MsgBox % "Error in " e.What ", which was called at line " e.Line
BadlyCodedFunc() {
throw Exception("Fail", -1)
}

View file

@ -0,0 +1,12 @@
foo()
If ErrorLevel
Msgbox calling foo failed with: %ErrorLevel%
foo()
{
If success
Return
Else
ErrorLevel = foo_error
Return
}

View file

@ -0,0 +1,10 @@
ON ERROR PROCerror(ERR, REPORT$) : END
ERROR 100, "User-generated exception"
END
DEF PROCerror(er%, rpt$)
PRINT "Exception occurred"
PRINT "Error number was " ; er%
PRINT "Error string was " rpt$
ENDPROC

View file

@ -0,0 +1,4 @@
struct MyException
{
// data with info about exception
};

View file

@ -0,0 +1,5 @@
#include <exception>
struct MyException: std::exception
{
char const* what() const throw() { return "description"; }
}

View file

@ -0,0 +1,17 @@
// this function can throw any type of exception
void foo()
{
throw MyException();
}
// this function can only throw the types of exceptions that are listed
void foo2() throw(MyException)
{
throw MyException();
}
// this function turns any exceptions other than MyException into std::bad_exception
void foo3() throw(MyException, std::bad_exception)
{
throw MyException();
}

View file

@ -0,0 +1,17 @@
try {
foo();
}
catch (MyException &exc)
{
// handle exceptions of type MyException and derived
}
catch (std::exception &exc)
{
// handle exceptions derived from std::exception, which were not handled by above catches
// e.g.
std::cerr << exc.what() << std::endl;
}
catch (...)
{
// handle any type of exception not handled by above catches
}

View file

@ -0,0 +1,27 @@
#include <setjmp.h>
enum { MY_EXCEPTION = 1 }; /* any non-zero number */
jmp_buf env;
void foo()
{
longjmp(env, MY_EXCEPTION); /* throw MY_EXCEPTION */
}
void call_foo()
{
switch (setjmp(env)) {
case 0: /* try */
foo();
break;
case MY_EXCEPTION: /* catch MY_EXCEPTION */
/* handle exceptions of type MY_EXCEPTION */
break;
default:
/* handle any type of exception not handled by above catches */
/* note: if this "default" section is not included, that would be equivalent to a blank "default" section */
/* i.e. any exception not caught above would be caught and ignored */
/* there is no way to "let the exception through" */
}
}

View file

@ -0,0 +1,82 @@
#include <stdio.h>
#include <setjmp.h>
#include <stdlib.h>
enum exceptions {
EXCEPTION_1 = 1,
EXCEPTION_2,
EXCEPTION_3
};
#define throw(exception) do { \
if (exp) \
longjmp(*exp, exception); \
printf("uncaught exception %d\n", exception); \
exit(exception); \
} while (0)
#define try(block, catch_block) \
{ \
jmp_buf *exception_outer = exp; \
jmp_buf exception_inner; \
exp = &exception_inner; \
int exception = setjmp(*exp); \
if (!exception) { \
do block while(0); \
exp = exception_outer; \
} else { \
exp = exception_outer; \
switch(exception) { \
catch_block \
default: \
throw(exception); \
} \
} \
}
#define catch(exception, block) \
case exception: do block while (0); break;
#define throws jmp_buf* exp
// define a throwing function
void g(throws) {
printf("g !\n");
throw(EXCEPTION_1);
printf("shouldnt b here\n");
}
void h(throws, int a)
{
printf("h %d!\n", a);
throw(EXCEPTION_2);
}
void f(throws) {
try({
g(exp); // call g with intention to catch exceptions
},
catch(EXCEPTION_1, {
printf("exception 1\n");
h(exp, 50); // will throw exception 2 inside this catch block
}))
}
int main(int argc, char* argv[])
{
throws = NULL; // define exception stack base
try({
f(exp);
},
catch(EXCEPTION_2, {
printf("exception 2\n");
})
catch(EXCEPTION_3, {
printf("exception 3\n");
}))
h(exp, 60); // will result in "uncaught exception"
return 0;
}

View file

@ -0,0 +1,8 @@
(try
(if (> (rand) 0.5)
(throw (RuntimeException. "oops!"))
(println "see this half the time")
(catch RuntimeException e
(println e)
(finally
(println "always see this"))

View file

@ -0,0 +1,5 @@
try {
foo();
} catch (Any e) {
// handle exception e
}

View file

@ -0,0 +1,4 @@
<cftry>
<cfcatch type="Database|...">
</cfcatch>
</cftry>

View file

@ -0,0 +1,14 @@
(define-condition unexpected-odd-number (error)
((number :reader number :initarg :number))
(:report (lambda (condition stream)
(format stream "Unexpected odd number: ~w."
(number condition)))))
(defun get-number (&aux (n (random 100)))
(if (not (oddp n)) n
(error 'unexpected-odd-number :number n)))
(defun get-even-number ()
(handler-case (get-number)
(unexpected-odd-number (condition)
(1+ (number condition)))))

View file

@ -0,0 +1,35 @@
import std.stdio;
/// Throw Exceptions
/// Stack traces are generated compiling with the -g switch.
void test1() {
throw new Exception("Sample Exception");
}
/// Catch Exceptions
void test2() {
try {
test1();
} catch (Exception ex) {
writeln(ex);
throw ex; // rethrow
}
}
/// Ways to implement finally
void test3() {
try test2();
finally writeln("test3 finally");
}
/// Or also with scope guards
void test4() {
scope(exit) writeln("Test4 done");
scope(failure) writeln("Test4 exited by exception");
scope(success) writeln("Test4 exited by return or function end");
test2();
}
void main() {
test4();
}

View file

@ -0,0 +1,4 @@
procedure Test;
begin
raise Exception.Create('Sample Exception');
end;

View file

@ -0,0 +1,11 @@
procedure Test2;
begin
try
test;
except
on E: Exception do begin // Filter by exception class
PrintLn(E.Message); // Showing exception message
raise; // Rethrowing
end;
end;
end;

View file

@ -0,0 +1,8 @@
procedure Test3;
begin
try
test2;
finally
PrintLn('Test3 finally');
end;
end;

View file

@ -0,0 +1,4 @@
procedure test;
begin
raise Exception.Create('Sample Exception');
end;

View file

@ -0,0 +1,9 @@
procedure test2;
begin
try
test;
except
ShowMessage(Exception(ExceptObject).Message); // Showing exception message
raise; // Rethrowing
end;
end;

View file

@ -0,0 +1,8 @@
procedure test3;
begin
try
test2;
finally
ShowMessage('test3 finally');
end;
end;

View file

@ -0,0 +1,15 @@
def nameOf(arg :int) {
if (arg == 43) {
return "Bob"
} else {
throw("Who?")
}
}
def catching(arg) {
try {
return ["ok", nameOf(arg)]
} catch exceptionObj {
return ["notok", exceptionObj]
}
}

View file

@ -0,0 +1,8 @@
? catching(42)
# value: ["not ok", problem: Who?]
? catching(43)
# value: ["ok", "Bob"]
? catching(45.7)
# value: ["not ok", problem: the float64 45.7 doesn't coerce to an int]

View file

@ -0,0 +1,15 @@
def nameOf(arg :int, ejector) {
if (arg == 43) {
return "Bob"
} else {
ejector("Who?")
}
}
def catching(arg) {
escape unnamed {
return ["ok", nameOf(arg, unnamed)]
} catch exceptionObj {
return ["notok", exceptionObj]
}
}

View file

@ -0,0 +1,8 @@
? catching(42)
# value: ["not ok", problem: Who?]
? catching(43)
# value: ["ok", "Bob"]
? catching(45.7)
# problem: the float64 45.7 doesn't coerce to an int

View file

@ -0,0 +1,11 @@
var nameTable := null
def nameOf(arg :int, ejector) {
if (nameTable == null) {
nameTable := <import:nameTableParser>.parseFile(<file:nameTable.txt>)
}
if (nameTable.maps(arg)) {
return nameTable[arg]
} else {
ejector(makeNotFoundException("Who?"))
}
}

View file

@ -0,0 +1,2 @@
: f ( -- ) 1 throw ." f " ; \ will throw a "1"
: g ( -- ) 0 throw ." g " ; \ does not throw

View file

@ -0,0 +1,4 @@
: report ( n -- ) ?dup if ." caught " . else ." no throw" then ;
: test ( -- )
['] f catch report
['] g catch report ;

View file

@ -0,0 +1,2 @@
cr test
'''caught 1 g no throw ok'''

View file

@ -0,0 +1 @@
10 ['] myfun catch if drop then

View file

@ -0,0 +1,19 @@
package main
import "fmt"
func foo() {
fmt.Println("let's foo...")
defer func() {
if err := recover(); err != nil {
fmt.Printf("Error: %v\n", err)
}
}()
panic("FAIL!")
fmt.Println("there's no point in going on.")
}
func main() {
foo()
fmt.Println("glad that's over.")
}

View file

@ -0,0 +1,2 @@
do {- ... -}
throwIO SomeException

View file

@ -0,0 +1,2 @@
if condition then 3
else throw SomeException

View file

@ -0,0 +1,2 @@
if condition then 3
else throwDyn myException

View file

@ -0,0 +1,4 @@
do
{- do IO computations here -}
`catch` \ex -> do
{- handle exception "ex" here -}

View file

@ -0,0 +1,4 @@
do
{- do IO computations here -}
`catchDyn` \ex -> do
{- handle exception "ex" here -}

View file

@ -0,0 +1,17 @@
import Exceptions
procedure main(A)
every i := !A do {
case Try().call{ write(g(i)) } of {
Try().catch(): {
x := Try().getException()
write(x.getMessage(), ":\n", x.getLocation())
}
}
}
end
procedure g(i)
if numeric(i) = 3 then Exception().throw("bad value of "||i)
return i
end

View file

@ -0,0 +1,7 @@
//Checked exception
public class MyException extends Exception {
//Put specific info in here
}
//Unchecked exception
public class MyRuntimeException extends RuntimeException {}

View file

@ -0,0 +1,7 @@
public void fooChecked() throws MyException {
throw new MyException();
}
public void fooUnchecked() {
throw new MyRuntimeException();
}

View file

@ -0,0 +1,15 @@
try {
fooChecked();
}
catch(MyException exc) {
//Catch only your specified type of exception
}
catch(Exception exc) {
//Catch any non-system error exception
}
catch(Throwable exc) {
//Catch everything including system errors (not recommended)
}
finally {
//This code is always executed after exiting the try block
}

View file

@ -0,0 +1,13 @@
public void foo() throws UnsupportedDataTypeException{
try{
throwsNumberFormatException();
//the following methods throw exceptions which extend IOException
throwsUnsupportedDataTypeException();
throwsFileNotFoundException();
}catch(FileNotFoundException | NumberFormatException ex){
//deal with these two Exceptions without duplicating code
}catch(IOException e){
//deal with the UnsupportedDataTypeException as well as any other unchecked IOExceptions
throw e;
}
}

View file

@ -0,0 +1,3 @@
function doStuff() {
throw new Error('Not implemented!');
}

View file

@ -0,0 +1,9 @@
try {
element.attachEvent('onclick', doStuff);
}
catch(e if e instanceof TypeError) {
element.addEventListener('click', doStuff, false);
}
finally {
eventSetup = true;
}

View file

@ -0,0 +1 @@
error("Something bad happened!")

View file

@ -0,0 +1,11 @@
function throw_error()
error("Whoops")
-- won't ever appear, due to previous error() call
return "hello!"
end
-- 'status' is false if 'throw_error' threw an error
-- otherwise, when everything went well, it will be true.
-- 'errmsg' contains the error message, plus filename and line number of where the error occured
status, errmsg = pcall(throw_error)
print("errmsg = ", errmsg)

View file

@ -0,0 +1,8 @@
function throw_error_with_argment(argument)
error(string.format("Whoops! argument = %s", argument))
-- won't ever appear, due to previous error() call
return "hello!"
end
status, errmsg = pcall(throw_error_with_argment, "foobar 123")
print("errmsg = ", errmsg)

View file

@ -0,0 +1,6 @@
function throw_error_with_argment(argument)
return "hello!"
end
status, errmsg = pcall(throw_error_with_argment, "foobar 123")
print("errmsg = ", errmsg)

View file

@ -0,0 +1,2 @@
>> error 'Help'
??? Help

View file

@ -0,0 +1,4 @@
class MyException extends Exception
{
// Custom exception attributes & methods
}

View file

@ -0,0 +1,4 @@
function throwsException()
{
throw new Exception('Exception message');
}

View file

@ -0,0 +1,5 @@
try {
throwsException();
} catch (Exception $e) {
echo 'Caught exception: ' . $e->getMessage();
}

View file

@ -0,0 +1,11 @@
# throw an exception
die "Danger, danger, Will Robinson!";
# catch an exception and show it
eval {
die "this could go wrong mightily";
};
print $@ if $@;
# rethrow
die $@;

View file

@ -0,0 +1,2 @@
# throw an exception
die "Danger, danger, Will Robinson!";

View file

@ -0,0 +1,6 @@
# catch an exception and show it
try {
die "this could go wrong mightily";
} catch {
print;
};

View file

@ -0,0 +1,2 @@
# rethrow (inside of catch)
die $_;

View file

@ -0,0 +1,4 @@
(catch 'thisLabel # Catch this label
(println 1) # Do some processing (print '1')
(throw 'thisLabel 2) # Abort processing and return '2'
(println 3) ) # This is never reached

View file

@ -0,0 +1,4 @@
import exceptions
class SillyError(exceptions.Exception):
def __init__(self,args=None):
self.args=args

View file

@ -0,0 +1,2 @@
class MyInvalidArgument(ValueError):
pass

View file

@ -0,0 +1,2 @@
def spam():
raise SillyError # equivalent to raise SillyError()

View file

@ -0,0 +1,2 @@
def spam():
raise SillyError, 'egg' # equivalent to raise SillyError('egg')

View file

@ -0,0 +1,2 @@
def spam():
raise SillyError('egg')

View file

@ -0,0 +1,10 @@
try:
foo()
except SillyError, se:
print se.args
bar()
else:
# no exception occurred
quux()
finally:
baz()

View file

@ -0,0 +1,10 @@
try:
foo()
except SillyError as se:
print(se.args)
bar()
else:
# no exception occurred
quux()
finally:
baz()

View file

@ -0,0 +1 @@
e <- simpleError("This is a simpleError")

View file

@ -0,0 +1,2 @@
stop("An error has occured")
stop(e) #where e is a simpleError, as above

View file

@ -0,0 +1,13 @@
tryCatch(
{
if(runif(1) > 0.5)
{
message("This doesn't throw an error")
} else
{
stop("This is an error")
}
},
error = function(e) message(paste("An error occured", e$message, sep = ": ")),
finally = message("This is called whether or not an exception occured")
)

View file

@ -0,0 +1,13 @@
#lang racket
;; define a new exception type
(struct exn:my-exception exn ())
;; handler that prints the message ("Hi!")
(define (handler exn)
(displayln (exn-message exn)))
;; install exception handlers
(with-handlers ([exn:my-exception? handler])
;; raise the exception
(raise (exn:my-exception "Hi!" (current-continuation-marks))))

View file

@ -0,0 +1,3 @@
# define an exception
class SillyError < Exception
end

View file

@ -0,0 +1,2 @@
class MyInvalidArgument < ArgumentError
end

View file

@ -0,0 +1,11 @@
# raise (throw) an exception
def spam
raise SillyError, 'egg'
end
# rescue (catch) an exception
begin
spam
rescue SillyError => se
puts se # writes 'egg' to stdout
end

View file

@ -0,0 +1,15 @@
begin
foo
rescue ArgumentError => e
# rescues a MyInvalidArgument or any other ArgumentError
bar
rescue => e
# rescues a StandardError
quack
else
# runs if no exception occurred
quux
ensure
# always runs
baz
end

View file

@ -0,0 +1,2 @@
# short way to rescue any StandardError
quotient = 1 / 0 rescue "sorry"

View file

@ -0,0 +1,7 @@
def foo
throw :done
end
catch :done do
foo
end

View file

@ -0,0 +1,22 @@
(define (me-errors xx exception)
(if (even? xx)
xx
(exception)))
;example that does nothing special on exception
(call/cc
(lambda (exception)
(me-errors 222 exception)
(display "I guess everything is alright")))
;example that laments oddness on exception
(call/cc
(lambda (all-ok) ;used to "jump" over exception handling
(call/cc
(lambda (exception-handle)
(me-errors 333 exception-handle)
(display "I guess everything is alright")
(all-ok)))
(display "oh my god it is ODD!")))

View file

@ -0,0 +1,5 @@
"exec" "gst" "-f" "$0" "$0" "$*"
"exit"
Transcript show: 'Throwing yawp'; cr.
self error: 'Yawp!'.

View file

@ -0,0 +1,7 @@
$ ./yawp.st
Throwing yawp
Object: nil error: Yawp!
Error(Exception)>>signal (AnsiExcept.st:216)
Error(Exception)>>signal: (AnsiExcept.st:226)
UndefinedObject(Object)>>error: (AnsiExcept.st:1565)
UndefinedObject>>executeStatements (yawp.st:5)

View file

@ -0,0 +1,9 @@
"exec" "gst" "-f" "$0" "$0" "$*"
"exit"
[
Transcript show: 'Throwing yawp'; cr.
self error: 'Yawp!'.
] on: Error do: [ :e |
Transcript show: 'Caught yawp'; cr.
].

View file

@ -0,0 +1,3 @@
$ ./yawp.st
Throwing yawp
Caught yawp

View file

@ -0,0 +1,15 @@
package require Tcl 8.5
# Throw
proc e {args} {
error "error message" "error message for stack trace" {errorCode list}
}
# Catch and rethrow
proc f {} {
if {[catch {e 1 2 3 4} errMsg options] != 0} {
return -options $options $errMsg
}
}
f