#include <stdio.h>
#include <stdlib.h>

typedef struct exception {
        int extype;
        char what[128];
} exception;

typedef struct exception_ctx {
        exception * exs;
        int size;
        int pos;
} exception_ctx;

exception_ctx * Create_Ex_Ctx(int length) {
        const int safety = 8; // alignment precaution.
        char * tmp = (char*) malloc(safety+sizeof(exception_ctx)+sizeof(exception)*length);
        if (! tmp) return NULL;
        exception_ctx * ctx = (exception_ctx*)tmp;
        ctx->size = length;
        ctx->pos = -1;
        ctx->exs = (exception*) (tmp + sizeof(exception_ctx));
        return ctx;
}

void Free_Ex_Ctx(exception_ctx * ctx) {
        free(ctx);
}

int Has_Ex(exception_ctx * ctx) {
        return (ctx->pos >= 0) ? 1 : 0;
}

int Is_Ex_Type(exception_ctx * exctx, int extype) {
        return (exctx->pos >= 0 && exctx->exs[exctx->pos].extype == extype) ? 1 : 0;
}

void Pop_Ex(exception_ctx * ctx) {
        if (ctx->pos >= 0) --ctx->pos;
}

const char * Get_What(exception_ctx * ctx) {
        if (ctx->pos >= 0) return ctx->exs[ctx->pos].what;
        return NULL;
}

int Push_Ex(exception_ctx * exctx, int extype, const char * msg) {
        if (++exctx->pos == exctx->size) {
                // Use last slot and report error.
                --exctx->pos;
                fprintf(stderr, "*** Error: Overflow in exception context.\n");
        }
        snprintf(exctx->exs[exctx->pos].what, sizeof(exctx->exs[0].what), "%s", msg);
        exctx->exs[exctx->pos].extype = extype;
        return -1;
}

//////////////////////////////////////////////////////////////////////

exception_ctx * GLOBALEX = NULL;
enum { U0_DRINK_ERROR = 10, U1_ANGRYBARTENDER_ERROR };

void baz(int n) {
        if (! n) {
                Push_Ex(GLOBALEX, U0_DRINK_ERROR , "U0 Drink Error. Insufficient drinks in bar Baz.");
                return;
        }
        else {
                Push_Ex(GLOBALEX, U1_ANGRYBARTENDER_ERROR , "U1 Bartender Error. Bartender kicked customer out of bar Baz.");
                return;
        }
}

void bar(int n) {
        fprintf(stdout, "Bar door is open.\n");
        baz(n);
        if (Has_Ex(GLOBALEX)) goto bar_cleanup;
        fprintf(stdout, "Baz has been called without errors.\n");
bar_cleanup:
        fprintf(stdout, "Bar door is closed.\n");
}

void foo() {
        fprintf(stdout, "Foo entering bar.\n");
        bar(0);
        while (Is_Ex_Type(GLOBALEX, U0_DRINK_ERROR)) {
                fprintf(stderr, "I am foo() and I deaall wrth U0 DriNk Errors with my own bottle... GOT oNE! [%s]\n", Get_What(GLOBALEX));
                Pop_Ex(GLOBALEX);
        }
        if (Has_Ex(GLOBALEX)) return;
        fprintf(stdout, "Foo left the bar.\n");
        fprintf(stdout, "Foo entering bar again.\n");
        bar(1);
        while (Is_Ex_Type(GLOBALEX, U0_DRINK_ERROR)) {
                fprintf(stderr, "I am foo() and I deaall wrth U0 DriNk Errors with my own bottle... GOT oNE! [%s]\n", Get_What(GLOBALEX));
                Pop_Ex(GLOBALEX);
        }
        if (Has_Ex(GLOBALEX)) return;
        fprintf(stdout, "Foo left the bar.\n");
}

int main(int argc, char ** argv) {
        exception_ctx * ctx = Create_Ex_Ctx(5);
        GLOBALEX = ctx;

        foo();
        if (Has_Ex(ctx)) goto main_ex;

        fprintf(stdout, "No errors encountered.\n");

main_ex:
        while (Has_Ex(ctx)) {
                fprintf(stderr, "*** Error: %s\n", Get_What(ctx));
                Pop_Ex(ctx);
        }
        Free_Ex_Ctx(ctx);
        return 0;
}


(defun factorial (n)
  (if (zerop n) 1 (* n (factorial (1- n)))))


import "os" for Process

var hq9plus = Fn.new { |code|
    var acc = 0
    var sb = ""
    for (c in code) {
        if (c == "h" || c == "H") {
            sb = sb + "Hello, world!\n"
        } else if (c == "q" || c == "Q") {
            sb = sb + code + "\n"
        } else if (c == "9") {
            for (i in 99..1) {
                var s = (i > 1) ? "s" : ""
                sb = sb + "%(i) bottle%(s) of beer on the wall\n"
                sb = sb + "%(i) bottle%(s) of beer\n"
                sb = sb + "Take one down, pass it around\n"
            }
            sb = sb + "No more bottles of beer on the wall!\n"
        } else if (c == "+") {
            acc = acc + 1
        } else {
            Fiber.abort("Code contains illegal operation '%(c)'")
        }
    }
    System.print(sb)
}

var args = Process.arguments
if (args.count != 1) {
    System.print("Please pass in the HQ9+ code to be executed.")
} else {
    hq9plus.call(args[0])
}


Program ExecuteSystemCommand;

uses
  SysUtils;
begin
  ExecuteProcess('/bin/ls', '-alh');
end.


; Execute a file - the equivalent of system() in stdio
;
; On entry, r1=>nul-terminated command string
; On exit,  VS=Couldn't fork
;           VC=Forked successfully, r0=return value
;
.CLIsystem
trap 2			; fork()
br   CLIchild		; Child process returns here
bcc  CLIparent		; Parent process returns here
mov  (sp)+,r1
tst  (sp)+
sev			; Couldn't fork, set V
rts  pc
.CLIparent
mov  r0,-(sp)		; Save child's PID
.CLIwait
trap 7			; wait()
cmp  r0,(sp)
beq  CLIfinished
cmp  r0,#&FFFF
bne  CLIwait		; Loop until child finished
.CLIfinished
tst  (sp)+		; Drop child's PID
mov  r1,r0		; R0=return value
mov  (sp)+,r1		; Restore R1
tst  (sp)+		; Drop original R0
swab r0			; Move return value to bottom byte
rts  pc

; CLI child process
; -----------------
.CLIchild
clr  -(sp)			; end of string array
mov  r1,-(sp)			; => command string
mov  #UXsh3,-(sp)		; => "-c"
mov  #UXsh2,-(sp)		; => "sh"
mov  #&890B,TRAP_BUF		; exec
mov  #UXsh1,TRAP_BUF+2		; => "/bin/sh"
mov  sp,TRAP_BUF+4		; => pointers to command strings
;mov  SV_ENVPTR,TRAP_BUF+6	; => "PATH=etc"
trap 0				; indir()
EQUW TRAP_BUF			; exec(shell, parameters)
add  #8,sp			; If we get back, we didn't fork, we spawned
mov  (sp)+,r1			; So, restore registers
clr  (sp)+			; and return exit value in R0
rts  pc

.UXsh1	EQUS "/bin/sh",0
.UXsh2	EQUS "sh",0
.UXsh3	EQUS "-c",0
ALIGN

.TRAP_BUF
EQUW 0
EQUW 0
EQUW 0
EQUW 0


my @results = qx(ls);  # run command and return STDOUT as a string

my @results = `ls`;    # same, alternative syntax

system "ls";           # run command and return exit status; STDOUT of command goes program STDOUT

print `ls`;            # same, but with back quotes

exec "ls";             # replace current process with another


without js
string cmd = iff(platform()=WINDOWS?"dir":"ls")
system(cmd)
integer res = system_exec("pause",4)


T SillyError
   String message
   F (message)
      .message = message

X.try
   X SillyError(‘egg’)
X.catch SillyError se
   print(se.message)


(
  (2 <)
  ((0 1 (dup rollup +)) dip pred times nip)
  unless
) :fib


using System; //Used for Exception and Console classes
class Exceptions
{
  class U0 : Exception { }
  class U1 : Exception { }
  static int i;
  static void foo()
  {
    for (i = 0; i < 2; i++)
      try
      {
        bar();
      }
      catch (U0) {
        Console.WriteLine("U0 Caught");
      }
  }
  static void bar()
  {
    baz();
  }
  static void baz(){
    if (i == 0)
      throw new U0();
    throw new U1();
  }

  public static void Main()
  {
    foo();
  }
}


#include <iostream>
class U0 {};
class U1 {};

void baz(int i)
{
    if (!i) throw U0();
    else throw U1();
}
void bar(int i) { baz(i); }

void foo()
{
    for (int i = 0; i < 2; i++)
    {
        try {
            bar(i);
        } catch(U0 e) {
		std::cout<< "Exception U0 caught\n";
        }
    }
}

int main() {
    foo();
    std::cout<< "Should never get here!\n";
    return 0;
}


(def U0 (ex-info "U0" {}))
(def U1 (ex-info "U1" {}))

(defn baz [x] (if (= x 0) (throw U0) (throw U1)))
(defn bar [x] (baz x))

(defn foo []
  (dotimes [x 2]
    (try
      (bar x)
      (catch clojure.lang.ExceptionInfo e
        (if (= e U0)
          (println "foo caught U0")
          (throw e))))))

(defn -main [& args]
  (foo))


        LDA  x
        BRZ  done_i   ; 0! = 1

        STA  i

loop_i: LDA  fact
        STA  n

        LDA  i
        SUB  one
        BRZ  done_i

        STA  j

loop_j: LDA  fact
        ADD  n
        STA  fact

        LDA  j
        SUB  one
        BRZ  done_j

        STA  j
        JMP  loop_j

done_j: LDA  i
        SUB  one
        STA  i

        JMP  loop_i

done_i: LDA  fact
        STP

one:         1

fact:        1

i:           0
j:           0
n:           0

x:           5


def factorial(x : Int)
    ans = 1
    (1..x).each do |i|
        ans *= i
    end
    return ans
end


;ds:si: pointer to asciiz string containing HQ9++ source code
ExecuteHQ9:
	push ax
	push dx
	push si
	push di
	push es
	push bx
	mov bx, si
	.interpret:
		lodsb
		cmp al, 'H'
		je .doHelloWorld
		cmp al, 'Q'
		je .doPrintCode
		cmp al, '9'
		je .doDrinkBeer
		cmp al, '+'
		je .doCounter
		pop bx
		pop es
		pop di
		pop si
		pop dx
		pop ax
		ret

	.doHelloWorld:
		push ds
		mov ax, cs
		mov ds, ax
		push si
		mov si, .dataHelloWorld
		call .printString
		pop si
		pop ds
		jmp .interpret

	.doPrintCode:
		push si
		mov si, bx
		call .printString
		pop si
		jmp .interpret

	.doDrinkBeer:
		push ds
		push si
		push ax
		mov ax, cs
		mov ds, ax
		mov ax, 99
		.beer_loop:
			call .printHexNumber
			mov si, .dataBeerSong1
			call .printString
			call .printHexNumber
			mov si, .dataBeerSong2
			call .printString
			dec ax
			call .printHexNumber
			mov si, .dataBeerSong3
			call .printString
			test ax, ax
			jnz .beer_loop
		pop ax
		pop si
		pop ds
		jmp .interpret

	.doCounter:
		push ax
		inc ax
		pop ax
		jmp .interpret

	.printString:
		push ax
		push si
	 .looping:
		lodsb
		test al, al
		jz .done
		mov ah, 0Eh
		int 10h
		jmp .looping
	 .done:
		pop si
		pop ax
		ret

	.printHexNumber:
			pusha
			push ds
			mov ax, cs
			mov ds, ax
			push word 0
			mov bx, ax
			xor dx, dx
			mov cx, 4r
	 .convert_loop:
			mov ax, bx
			and ax, 0Fh
			cmp ax, 9
			ja  .greater_than_9
			add ax, '0'
			jmp .converted
	 .greater_than_9:
			add ax, 'A'-0Ah
	 .converted:
			push ax
			shr bx, 4
			dec cx
			jnz .convert_loop
	 .popoff:
			pop ax
			cmp ax, 0
			je .done
			mov ah, 0Eh
			int 10h
			jmp .popoff
		.done:
			pop ds
			popa
			ret

	.dataHelloWorld: db "Hello World!", 0
	.dataBeerSong1: db " bottles of beer on the wall ", 0
	.dataBeerSong2: db " bottles of beer", 13, 10, "Take one down, pass it around "
	.dataBeerSong3: db 0, " bottles of beer on the wall", 0


<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
	<!-- bottles.xsl defines $entire-bottles-song -->
	<xsl:import href="bottles.xsl"/>

	<xsl:output method="text" encoding="utf-8"/>

	<xsl:variable name="hello-world">
		<xsl:text>Hello, world!
</xsl:text>
	</xsl:variable>

	<!-- Main template -->
	<xsl:template match="/">
		<xsl:call-template name="run">
			<xsl:with-param name="code" select="string(.)"/>
		</xsl:call-template>
	</xsl:template>

	<!-- Runs HQ9+ code from string starting at given index (default 1) -->
	<xsl:template name="run">
		<xsl:param name="code"/>
		<xsl:param name="starting-at" select="1"/>

		<!-- Fetches instruction and forces to upper-case -->
		<xsl:variable name="inst" select="translate(substring($code, $starting-at, 1), 'hq', 'HQ')"/>

		<!-- Only if not at end -->
		<xsl:if test="$inst != ''">
			<xsl:choose>
				<xsl:when test="$inst = 'H'">
					<xsl:value-of select="$hello-world"/>
				</xsl:when>
				<xsl:when test="$inst = 'Q'">
					<xsl:value-of select="$code"/>
					<xsl:text>
</xsl:text>
				</xsl:when>
				<xsl:when test="$inst = '9'">
					<xsl:value-of select="$entire-bottles-song"/>
				</xsl:when>
				<xsl:when test="$inst = '+'">
					<!-- XSLT has no meaningful equivalent of write-only variables -->
				</xsl:when>
				<!-- Otherwise, do nothing -->
			</xsl:choose>

			<!-- Proceed with next instruction -->
			<xsl:call-template name="run">
				<xsl:with-param name="code" select="$code"/>
				<xsl:with-param name="starting-at" select="$starting-at + 1"/>
			</xsl:call-template>
		</xsl:if>
	</xsl:template>
</xsl:stylesheet>


int main(){
   // Process.run was added in Pike 7.8 as a wrapper to simplify the use of Process.create_process()
   mapping response = Process.run("ls -l");
   // response is now a map containing 3 fields
   // stderr, stdout, and exitcode. We want stdout.
   write(response["stdout"] + "\n");

   // with older versions of pike it's a bit more complicated:
   Stdio.File stdout = Stdio.File();
   Process.create_process(({"ls", "-l"}), ([ "stdout" : stdout->pipe() ]) );
   write(stdout->read() + "\n");
}


;syscall for creating a new file.
mov dx,offset filename
mov cx,0
mov ah,5Bh
int 21h
;if error occurs, will return carry set and error code in ax
;Error code 03h = path not found
;Error code 04h = Too many open files
;Error code 05h = Access denied
;Error code 50h = File already exists

jnc noError                       ;continue with program

     cmp ax,03h
     je PathNotFoundError         ;unimplemented exception handler

     cmp ax,04h
     je TooManyOpenFilesError

     cmp ax,05h
     je AccessDeniedError

     cmp ax,50h
     je FileAlreadyExistsError

noError:


try {
    var lines = readfile ("input.txt")
    process (lines)
} catch (e) {
   do_somthing(e)
}


fibonacci = function(n)
    if n < 2 then return n
    n1 = 0
    n2 = 1
    for i in range(n-1, 1)
        ans = n1 + n2
        n1 = n2
        n2 = ans
    end for
    return ans
end function

print fibonacci(6)


(define-condition user-condition-1 (error) ())
(define-condition user-condition-2 (error) ())

(defun foo ()
  (dolist (type '(user-condition-1 user-condition-2))
    (handler-case
        (bar type)
      (user-condition-1 (c)
        (format t "~&foo: Caught: ~A~%" c)))))

(defun bar (type)
  (baz type))

(defun baz (type)
  (error type))    ; shortcut for (error (make-condition type))

(trace foo bar baz)
(foo)


class U0 < Exception
end

class U1 < Exception
end

def foo
  2.times do |i|
    begin
      bar(i)
    rescue e : U0
      puts "rescued #{e}"
    end
  end
end

def bar(i : Int32)
    baz(i)
end

def baz(i : Int32)
  raise U0.new("this is u0") if i == 0
    raise U1.new("this is u1") if i == 1
end

foo


class U0 : Exception {
    this() @safe pure nothrow { super("U0 error message"); }
}

class U1 : Exception {
    this() @safe pure nothrow { super("U1 error message"); }
}

void foo() {
    import std.stdio;

    foreach (immutable i; 0 .. 2) {
        try {
            i.bar;
        } catch (U0) {
            "Function foo caught exception U0".writeln;
        }
    }
}

void bar(in int i) @safe pure {
    i.baz;
}

void baz(in int i) @safe pure {
    throw i ? new U1 : new U0;
}

void main() {
    foo;
}


uint factorial(in uint n) pure nothrow @nogc
in {
    assert(n <= 12);
} body {
    uint result = 1;
    foreach (immutable i; 1 .. n + 1)
        result *= i;
    return result;
}

// Computed and printed at compile-time.
pragma(msg, 12.factorial);

void main() {
    import std.stdio;

    // Computed and printed at run-time.
    12.factorial.writeln;
}


fcn runHQ9(code){
   acc:=0;
   foreach c in (code){
      switch(c){
	 case("H"){ println("hello, world"); }
	 case("Q"){ print(code); }
	 case("+"){ acc+=1; }
	 case("9"){ wall_O_beer(); }
      }
   }
}
fcn wall_O_beer(){
   [99..0,-1].pump(fcn(n){
      println(beers(n), " on the wall, ", beers(n).toLower(), ".\n",
	 n==0 and ("Go to the store and buy some more, 99 bottles of beer") or
	 ("Take one down and pass it around, " + beers(n-1).toLower()),
	 " on the wall.\n")
   });
}
fcn beers(n){
    (n==0 and "No more bottles" or (n==1 and "1 bottle" or "" + n + " bottles"))
    + " of beer"
}


ImportC "msvcrt.lib"
  system(str.p-ascii)
EndImport

If OpenConsole()
  system("dir & pause")

  Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
  Input()
  CloseConsole()
EndIf


import os
exit_code = os.system('ls')       # Just execute the command, return a success/fail code
output    = os.popen('ls').read() # If you want to get the output data. Deprecated.


$ \
import os
exit_code = os.system('ls')
\ python


#lang racket

;; simple execution of a shell command
(system "ls")

;; capture output
(string-split (with-output-to-string (λ() (system "ls"))) "\n")

;; Warning: passing random string to be run in a shell is a bad idea!
;; much safer: avoids shell parsing, arguments passed separately
(system* "/bin/ls" "-l")

;; avoid specifying the executable path
(system* (find-executable-path "/bin/ls") "-l")


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;
}


COMMENT
  Define an general event handling mechanism on MODE OBJ:
  * try to parallel pythons exception handling flexibility
END COMMENT

COMMENT
  REQUIRES:
    MODE OBJ # These can be a UNION of REF types #
    OP OBJIS
  PROVIDES:
    OP ON, RAISE, RESET
    PROC obj on, obj raise, obj reset
END COMMENT

# define object related to OBJ EVENTS #
MODE
  RAISEOBJ = PROC(OBJ)VOID, RAWMENDOBJ = PROC(OBJ)BOOL,
  MENDOBJ = UNION(RAWMENDOBJ, PROC VOID), # Generalise: Allow PROC VOID (a GOTO) as a short hand #
  NEWSCOPEOBJ = STRUCT(REF NEWSCOPEOBJ up, FLEXOBJ obj flex, FLEXEVENTOBJ event flex, MENDOBJ mended),
  SCOPEOBJ = REF NEWSCOPEOBJ;

MODE FLEXOBJ=FLEX[0]OBJ;

# Provide an INIT to convert a GO TO to a MEND ... useful for direct aborts #
OP INITMENDOBJ = (PROC VOID go to)MENDOBJ: (go to; SKIP);

SCOPEOBJ obj scope end = NIL;
SCOPEOBJ obj scope begin := obj scope end; # INITialise stack #
OBJ obj any = EMPTY;
EVENTOBJ obj event any = NIL;

# Some crude Singly Linked-List manipulations of the scopes, aka stack ... #
# An event/mended can be shared for all OBJ of the same type: #
PRIO INITAB = 1, +=: = 1;
OP INITAB = (SCOPEOBJ lhs, MENDOBJ obj mend)SCOPEOBJ:
  lhs := (obj scope end, obj any, obj event any, obj mend);

OP INITSCOPE = (MENDOBJ obj mend)SCOPEOBJ: HEAP NEWSCOPEOBJ INITAB obj mend;
OP +=: = (SCOPEOBJ item, REF SCOPEOBJ rhs)SCOPEOBJ: ( up OF item := rhs; rhs := item );
OP +=: = (MENDOBJ mend, REF SCOPEOBJ rhs)SCOPEOBJ: INITSCOPE mend +=: rhs;
#OP -=: = (REF SCOPEOBJ scope)SCOPEOBJ: scope := up OF scope;#

COMMENT Restore the prio event scope: ~ END COMMENT
PROC obj reset = (SCOPEOBJ up scope)VOID: obj scope begin := up scope;
MENDOBJ obj unmendable = (OBJ obj)BOOL: FALSE;

MODE NEWEVENTOBJ = STRUCT( # the is simple a typed place holder #
  SCOPEOBJ scope,
  STRING description,
  PROC (OBJ #obj#, MENDOBJ #obj mend#)SCOPEOBJ on,
  PROC (OBJ #obj#, STRING #msg#)VOID raise
), EVENTOBJ = REF NEWEVENTOBJ;

MODE FLEXEVENTOBJ = FLEX[0]EVENTOBJ;

COMMENT Define how to catch an event:
    obj - IF obj IS NIL then mend event on all OBJects
    obj mend - PROC to call to repair the object
    return the prior event scope
END COMMENT
PROC obj on = (FLEXOBJ obj flex, FLEXEVENTOBJ event flex, MENDOBJ mend)SCOPEOBJ: (
  mend +=: obj scope begin;
  IF obj any ISNTIN obj flex THEN obj flex OF obj scope begin := obj flex FI;
  IF obj event any ISNTIN event flex THEN event flex OF obj scope begin := event flex FI;
  up OF obj scope begin
);

PRIO OBJIS = 4, OBJISNT = 4; # pick the same PRIOrity as EQ and NE #
OP OBJISNT = (OBJ a,b)BOOL: NOT(a OBJIS b);

PRIO ISIN = 4, ISNTIN = 4;
OP ISNTIN = (OBJ obj, FLEXOBJ obj flex)BOOL: (
  BOOL isnt in := FALSE;
  FOR i TO UPB obj flex WHILE isnt in := obj OBJISNT obj flex[i] DO SKIP OD;
  isnt in
);
OP ISIN = (OBJ obj, FLEXOBJ obj flex)BOOL: NOT(obj ISNTIN obj flex);

OP ISNTIN = (EVENTOBJ event, FLEXEVENTOBJ event flex)BOOL: (
  BOOL isnt in := TRUE;
  FOR i TO UPB event flex WHILE isnt in := event ISNT event flex[i] DO SKIP OD;
  isnt in
);
OP ISIN = (EVENTOBJ event, FLEXEVENTOBJ event flex)BOOL: NOT(event ISNTIN event flex);

COMMENT Define how to raise an event, once it is raised try and mend it:
  if all else fails produce an error message and stop
END COMMENT
PROC obj raise = (OBJ obj, EVENTOBJ event, STRING msg)VOID:(
  SCOPEOBJ this scope := obj scope begin;
# until mended this event should cascade through scope event handlers/members #
  FOR i WHILE this scope ISNT SCOPEOBJ(obj scope end) DO
    IF (obj any ISIN obj flex OF this scope OR obj ISIN obj flex OF this scope ) AND
       (obj event any ISIN event flex OF this scope OR event ISIN event flex OF this scope)
    THEN
      CASE mended OF this scope IN
        (RAWMENDOBJ mend):IF mend(obj) THEN break mended FI,
        (PROC VOID go to): (go to; stop)
      OUT put(stand error, "undefined: raise stop"); stop
      ESAC
    FI;
    this scope := up OF this scope
  OD;
  put(stand error, ("OBJ event: ",msg)); stop; FALSE
EXIT
  break mended: TRUE
);

CO define ON and some useful(?) RAISE OPs CO
PRIO ON = 1, RAISE = 1;
OP ON = (MENDOBJ mend, EVENTOBJ event)SCOPEOBJ: obj on(obj any, event, mend),
   RAISE = (OBJ obj, EVENTOBJ event)VOID: obj raise(obj, event, "unnamed event"),
   RAISE = (OBJ obj, MENDOBJ mend)VOID: ( mend ON obj event any; obj RAISE obj event any),
   RAISE = (EVENTOBJ event)VOID: obj raise(obj any, event, "unnamed event"),
   RAISE = (MENDOBJ mend)VOID: ( mend ON obj event any; RAISE obj event any),
   RAISE = (STRING msg, EVENTOBJ event)VOID: obj raise(obj any, event, msg);
OP (SCOPEOBJ #up scope#)VOID RESET = obj reset;

SKIP


function var int: fibonacci(int: n) =
  let {
    array[0..n] of var int: fibonacci;
    constraint forall(a in 0..n)(
      fibonacci[a] = if (a == 0 \/ a == 1) then
        a
      else
        fibonacci[a-1]+fibonacci[a-2]
      endif
    )
  } in fibonacci[n];

var int: fib = fibonacci(6);
solve satisfy;
output [show(fib),"\n"];


program ExceptionsInNestedCall;

{$APPTYPE CONSOLE}

uses SysUtils;

type
  U0 = class(Exception)
  end;
  U1 = class(Exception)
  end;

procedure Baz(i: Integer);
begin
  if i = 0 then
    raise U0.Create('U0 Error message')
  else
    raise U1.Create('U1 Error message');
end;

procedure Bar(i: Integer);
begin
  Baz(i);
end;

procedure Foo;
var
  i: Integer;
begin
  for i := 0 to 1 do
  begin
    try
      Bar(i);
    except
      on E: U0 do
        Writeln('Exception ' + E.ClassName + ' caught');
    end;
  end;
end;

begin
  Foo;
end.


type Exception1 = class (Exception) end;
type Exception2 = class (Exception) end;

procedure Baz(i : Integer);
begin
   if i=0 then
      raise new Exception1('Error message 1')
   else raise new Exception2('Error message 2');
end;

procedure Bar(i : Integer);
begin
   Baz(i);
end;

procedure Foo;
var
   i : Integer;
begin
   for i:=0 to 2 do begin
      try
         Bar(i);
      except
         on E : Exception1 do
            PrintLn(E.ClassName+' caught');
      end;
   end;
end;

Foo;


int fact(int n) {
  if(n<0) {
    throw new IllegalArgumentException('Argument less than 0');
  }
  return n==0 ? 1 : n*fact(n-1);
}

main() {
  print(fact(10));
  print(fact(-1));
}


[*
 * (n) lfx -- (factorial of n)
 *]sz
[
 1 Sp           [product = 1]sz
 [              [Loop while 1 < n:]sz
  d lp * sp      [product = n * product]sz
  1 -            [n = n - 1]sz
  d 1 <f
 ]Sf d 1 <f
 Lfsz           [Drop loop.]sz
 sz             [Drop n.]sz
 Lp             [Push product.]sz
]sf

[*
 * For example, print the factorial of 50.
 *]sz
50 lfx psz


run "ls" orelse .die; # output to stdout

my @ls = qx/ls/;    # output to variable

my $cmd = 'ls';
@ls = qqx/$cmd/;  # same thing with interpolation


; Capture output to string variable:

x: ""  call/output "dir" x
print x

; The 'console' refinement displays the command output on the REBOL command line.

call/console "dir *.r"
call/console "ls *.r"

call/console "pause"

; The 'shell' refinement may be necessary to launch some programs.

call/shell "notepad.exe"


call/show %pause        ;The /show refinement forces the display of system's shell window (Windows only).
call/show %dir
call/show %notepad.exe


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


try
    BadlyCodedFunc()
catch e
    MsgBox % "Error in " e.What ", which was called at line " e.Line

BadlyCodedFunc() {
    throw Exception("Fail", -1)
}


      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


	.text
main:	li	$v0, 5		# read integer from input. The read integer will be stroed in $v0
	syscall

	beq	$v0, 0, is1
	beq	$v0, 1,	is1

	li	$s4, 1		# the counter which has to equal to $v0

	li	$s0, 1
	li	$s1, 1

loop:	add	$s2, $s0, $s1
	addi	$s4, $s4, 1
	beq	$v0, $s4, iss2

	add	$s0, $s1, $s2
	addi	$s4, $s4, 1
	beq	$v0, $s4, iss0

	add	$s1, $s2, $s0
	addi	$s4, $s4, 1
	beq	$v0, $s4, iss1

	b 	loop

iss0:	move	$a0, $s0
	b	print

iss1:	move	$a0, $s1
	b	print

iss2:	move	$a0, $s2
	b	print

is1:	li	$a0, 1
	b 	print

print:	li	$v0, 1
	syscall
	li	$v0, 10
	syscall


var bazCallCount = 0

func baz() {
    bazCallCount += 1
    if bazCallCount == 1 {
        throw @BazCall1()
    } else if bazCallCount == 2 {
        throw @BazCall2()
    }
}

func bar() {
    baz()
}

func foo() {
    var calls = 2
    while calls > 0 {
        try {
            bar()
        } catch {
            @BazCall1() => print("BazzCall1 caught.")
        }
        calls -= 1
    }
}

foo()


(define (foo)
  (for ((i 2))
    (try
    (bar i)
    (catch (id message)
      (if (= id 'U0)
         (writeln message 'catched)
         (error id "not catched"))))))

(define (bar i)
    (baz i))

(define (baz i)
    (if (= i 0)
        (throw 'U0 "U0 raised")
        (throw 'U1 "U1 raised")))

(foo) →
    "U0 raised"     catched
    👓 error: U1 not catched


record U0 type Exception
end

record U1 type Exception
end

program Exceptions

    function main()
        foo();
    end

    function foo()
        try
            bar();
        onException(ex U0)
            SysLib.writeStdout("Caught a U0 with message: '" :: ex.message :: "'");
        end
        bar();
    end

    function bar()
        baz();
    end

    firstBazCall boolean = true;
    function baz()
        if(firstBazCall)
            firstBazCall = false;
            throw new U0{message = "This is the U0 exception"};
        else
            throw new U1{message = "This is the U1 exception"};
        end
    end
end


class MAIN
    inherit EXCEPTIONS

    creation foo

feature {ANY}
    baz_calls: INTEGER

    feature foo is
        do
            Current.bar
        rescue
            if is_developer_exception_of_name("U0") then
                baz_calls := 1
                print("Caught U0 exception.%N")
                retry
            end
            if is_developer_exception then
                print("Won't catch ")
                print(developer_exception_name)
                print(" exception...%N")
            end
        end

    feature bar is
        do
            Current.baz
        end

    feature baz is
        do
            if baz_calls = 0 then
                raise("U0")
            else
                raise("U1")
            end
        end
end


program Factorial1;

{$APPTYPE CONSOLE}

function FactorialIterative(aNumber: Integer): Int64;
var
  i: Integer;
begin
  Result := 1;
  for i := 1 to aNumber do
    Result := i * Result;
end;

begin
  Writeln('5! = ', FactorialIterative(5));
end.


string = `ls`
# runs command and returns its STDOUT as a string
string = %x{ls}
# ditto, alternative syntax

system "ls"
# runs command and returns its exit status; its STDOUT gets output to our STDOUT

print `ls`
#The same, but with back quotes

exec "ls"
# replace current process with another

# call system command and read output asynchronously
io = IO.popen('ls')
# ... later
io.each {|line| puts line}


print shell$("ls")  ' prints the returned data from the OS
a$ =  shell$("ls")  ' holds returned data in a$


use std::process::Command;
fn main() {
    let output = Command::new("ls").output().unwrap_or_else(|e| {
        panic!("failed to execute process: {}", e)
    });
    println!("{}", String::from_utf8_lossy(&output.stdout));
}


import scala.sys.process.Process
Process("ls", Seq("-oa"))!


$ include "seed7_05.s7i";
  include "shell.s7i";

const proc: main is func
  begin
    cmd_sh("ls");
  end func;


try
    1 / 0 # Throw an exception
    print("unreachable code")
catch
    print("An error occured!")
end


( ( MyFunction
  =   someText XMLstuff
    .   (   get$!arg:?someText
          & get$("CorporateData.xml",X,ML):?XMLstuff
        |     out
            $ ( str
              $ ( "Something went wrong when reading your file \""
                  !arg
                  "\". Or was it the Corporate Data? Hard to say. Anyhow, now I throw you out."
                )
              )
          & ~
        )
      & contemplate$(!someText,!XMLstuff)
  )
& MyFunction$"Tralula.txt"
);


#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" */
  }
}


def fibonacci(n:int)
    return n if n < 2
    fibPrev = 1
    fib = 1
    3.upto(Math.abs(n)) do
        oldFib = fib
        fib = fib + fibPrev
        fibPrev = oldFib
    end
    fib * (n<0 ? int(Math.pow(n+1, -1)) : 1)
end

puts fibonacci 1
puts fibonacci 2
puts fibonacci 3
puts fibonacci 4
puts fibonacci 5
puts fibonacci 6
puts fibonacci 7


import extensions;

class U0 : Exception
{
    constructor new()
        <= new();
}

class U1 : Exception
{
    constructor new()
        <= new();
}

singleton Exceptions
{
    static int i;

    bar()
        <= baz();

    baz()
    {
        if (i == 0)
        {
            U0.raise()
        }
        else
        {
            U1.raise()
        }
    }

    foo()
    {
        for(i := 0, i < 2, i += 1)
        {
            try
            {
                self.bar()
            }
            catch(U0 e)
            {
                console.printLine("U0 Caught")
            }
        }
    }
}

public program()
{
    Exceptions.foo()
}


defmodule U0, do: defexception [:message]
defmodule U1, do: defexception [:message]

defmodule ExceptionsTest do
  def foo do
    Enum.each([0,1], fn i ->
      try do
        bar(i)
      rescue
        U0 -> IO.puts "U0 rescued"
      end
    end)
  end

  def bar(i), do: baz(i)

  def baz(0), do: raise U0
  def baz(1), do: raise U1
end

ExceptionsTest.foo


-module( exceptions_catch ).

-export( [task/0] ).

task() -> [foo(X) || X<- lists:seq(1, 2)].

baz( 1 ) -> erlang:throw( u0 );
baz( 2 ) -> erlang:throw( u1 ).

foo( N ) ->
	try
	baz( N )

	catch
	_:u0 -> io:fwrite( "Catched ~p~n", [u0] )

	end.


USING: combinators.extras continuations eval formatting kernel ;
IN: rosetta-code.nested-exceptions

ERROR: U0 ;
ERROR: U1 ;

: baz ( -- )
    "IN: rosetta-code.nested-exceptions : baz ( -- ) U1 ;"
    ( -- ) eval U0 ;

: bar ( -- ) baz ;

: foo ( -- )
    [
        [ bar ] [
            dup T{ U0 } =
            [ "%u recovered\n" printf ] [ rethrow ] if
        ] recover
    ] twice ;

foo


/* Note that ulong is 32 bits, so fac(12) is the largest
 * supported value. This is why the input parameter
 * is a byte. The parameters are all unsigned. */
proc nonrec fac(byte n) ulong:
    byte i;
    ulong rslt;
    rslt := 1;
    for i from 2 upto n do
        rslt := rslt * i
    od;
    rslt
corp

proc nonrec main() void:
    byte i;
    for i from 0 upto 12 do
        writeln(i:2, "! = ", fac(i):9)
    od
corp


select "std"
factorial = 1
n = readln()
for(i=1,i<=n,++i)
        {
            factorial = factorial * i
        }
           showln "factorial of " + n + " is " + factorial


# Pipe in read-only mode
%p(ls).open_r.each { |line|
    print line;
};

var str1 = `ls`;         # backtick: returns a string
var str2 = %x(ls);       # ditto, alternative syntax

Sys.system('ls');   # system: executes a command and prints the result
Sys.exec('ls');     # replaces current process with another


public class MyException : Exception
{
  // data with info about exception
};


struct MyException
{
  // data with info about exception
};


(try
  (if (> (rand) 0.5)
    (throw (RuntimeException. "oops!"))
  (println "see this half the time")
  (catch RuntimeException e
    (println e)
  (finally
    (println "always see this"))


const class U0 : Err
{
  new make () : super ("U0") {}
}

const class U1 : Err
{
  new make () : super ("U1") {}
}

class Main
{
  Int bazCalls := 0

  Void baz ()
  {
    bazCalls += 1
    if (bazCalls == 1)
      throw U0()
    else
      throw U1()
  }

  Void bar ()
  {
    baz ()
  }

  Void foo ()
  {
    2.times
    {
      try
      {
        bar ()
      }
      catch (U0 e)
      {
        echo ("Caught U0")
      }
    }
  }

  public static Void main ()
  {
    Main().foo
  }
}


' FB 1.05.0 Win64

Enum ErrorTypes
  U0 = 1000
  U1
End Enum

Function errorName(ex As ErrorTypes) As String
  Select Case As Const ex
    Case U0
      Return "U0"
    Case U1
      Return "U1"
  End Select
End Function

Sub catchError(ex As ErrorTypes)
   Dim e As Integer = Err '' cache the error number
   If e = ex Then
     Print "Error "; errorName(ex); ", number"; ex; " caught"
   End If
End Sub

Sub baz()
  Static As Integer timesCalled = 0 '' persisted between procedure calls
  timesCalled += 1
  If timesCalled = 1 Then
    err = U0
  Else
    err = U1
  End if
End Sub

Sub bar()
  baz
End Sub

Sub foo()
  bar
  catchError(U0) '' not interested in U1, assumed non-fatal
  bar
  catchError(U0)
End Sub

Foo
Print
Print "Press any key to quit"
Sleep


// Outline for a try/catch-like exception mechanism in Go
//
// As all Go programmers should know, the Go authors are sharply critical of
// the try/catch idiom and consider it bad practice in general.
// See http://golang.org/doc/go_faq.html#exceptions

package main

import (
    "fmt"
    "runtime"
    "strings"
)

// trace is for pretty output for the Rosetta Code task.
// It would have no place in a practical program.
func trace(s string) {
    nc := runtime.Callers(2, cs)
    f := runtime.FuncForPC(cs[0])
    fmt.Print(strings.Repeat("  ", nc-3), f.Name()[5:], ": ", s, "\n")
}

var cs = make([]uintptr, 10)

type exception struct {
    name    string
    handler func()
}

// try implents the try/catch-like exception mechanism.  It takes a function
// to be called, and a list of exceptions to catch during the function call.
// Note that for this simple example, f has no parameters.  In a practical
// program it might, of course.  In this case, the signature of try would
// have to be modified to take these parameters and then supply them to f
// when it calls f.
func try(f func(), exs []exception) {
    trace("start")
    defer func() {
        if pv := recover(); pv != nil {
            trace("Panic mode!")
            if px, ok := pv.(exception); ok {
                for _, ex := range exs {
                    if ex.name == px.name {
                        trace("handling exception")
                        px.handler()
                        trace("panic over")
                        return
                    }
                }
            }
            trace("can't recover this one!")
            panic(pv)
        }
    }()
    f()
    trace("complete")
}

func main() {
    trace("start")
    foo()
    trace("complete")
}

// u0, u1 declared at package level so they can be accessed by any function.
var u0, u1 exception

// foo.  Note that function literals u0, u1 here in the lexical scope
// of foo serve the purpose of catch blocks of other languages.
// Passing u0 to try serves the purpose of the catch condition.
// While try(bar... reads much like the try statement of other languages,
// this try is an ordinary function.  foo is passing bar into try,
// not calling it directly.
func foo() {
    trace("start")
    u0 = exception{"U0", func() { trace("U0 handled") }}
    u1 = exception{"U1", func() { trace("U1 handled") }}
    try(bar, []exception{u0})
    try(bar, []exception{u0})
    trace("complete")
}

func bar() {
    trace("start")
    baz()
    trace("complete")
}

var bazCall int

func baz() {
    trace("start")
    bazCall++
    switch bazCall {
    case 1:
        trace("panicking with execption U0")
        panic(u0)
    case 2:
        trace("panicking with execption U1")
        panic(u1)
    }
    trace("complete")
}


function IterativeFactorial(n : Integer) : Integer;
var
   i : Integer;
begin
   Result := 1;
   for i := 2 to n do
      Result *= i;
end;


!dir

* print a message and wait
!echo Ars Longa Vita Brevis & pause

* load Excel from Stata
!start excel

* run a Python program (Python must be installed and accessible in the PATH environment variable)
!python preprocessing.py

* load Windows Notepad
winexec notepad


$$ MODE TUSCRIPT
system=SYSTEM ()
IF (system=="WIN") THEN
EXECUTE "dir"
ELSEIF (system.sw."LIN") THEN
EXECUTE "ls -l"
ENDIF


decl string<> arg
decl string<> output
decl iodevice iod

append "ls" arg
set iod (ursa.util.process.start arg)
set output (iod.readlines)

for (decl int i) (< i (size output)) (inc i)
        out output<i> endl console
end for


#import std
#import cli

#executable ('parameterized','')

myls = <.file$[contents: --<''>]>@hm+ (ask bash)/0+ -[ls --color=no]-!


try {
  foo();
} catch (Any e) {
  // handle exception e
}


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


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();
}


fun fib n =
    let
	fun fib' (0,a,b) = a
	  | fib' (n,a,b) = fib' (n-1,a+b,a)
    in
	fib' (n,0,1)
    end


import Control.Monad.Error
import Control.Monad.Trans (lift)

-- Our "user-defined exception" tpe
data MyError = U0 | U1 | Other deriving (Eq, Read, Show)

-- Required for any error type
instance Error MyError where
  noMsg    = Other
  strMsg _ = Other

-- Throwing and catching exceptions implies that we are working in a monad. In
-- this case, we use ErrorT to support our user-defined exceptions, wrapping
-- IO to be able to report the happenings. ('lift' converts ErrorT e IO a
-- actions into IO a actions.)

foo = do lift (putStrLn "foo")
         mapM_ (\toThrow -> bar toThrow                      -- the protected call
                              `catchError` \caught ->        -- the catch operation
                                                             -- ↓ what to do with it
                                 case caught of U0 -> lift (putStrLn "foo caught U0")
                                                _  -> throwError caught)
               [U0, U1]                                      -- the two exceptions to throw

bar toThrow = do lift (putStrLn " bar")
                 baz toThrow

baz toThrow = do lift (putStrLn "  baz")
                 throwError toThrow

-- We cannot use exceptions without at some outer level choosing what to do
-- if an exception propagates all the way up. Here we just print the exception
-- if there was one.
main = do result <- runErrorT foo
          case result of
            Left e  -> putStrLn ("Caught error at top level: " ++ show e)
            Right v -> putStrLn ("Return value: " ++ show v)


import Exceptions

class U0 : Exception()
    method getMessage()
        return "U0: " || (\message | "unknown")
    end
end

class U1 : Exception()
    method getMessage()
        return "U1: " || (\message | "unknown")
    end
end

procedure main()
    # (Because Exceptions are not built into Unicon, uncaught
    #   exceptions are ignored.  This clause will catch any
    #   exceptions not caught farther down in the code.)
    case Try().call{ foo() } of {
        Try().catch(): {
            ex := Try().getException()
            write(ex.getMessage(), ":\n", ex.getLocation())
            }
        }
end

procedure foo()
    every 1|2 do {
        case Try().call{ bar() } of {
            Try().catch("U0"): {
                ex := Try().getException()
                write(ex.getMessage(), ":\n", ex.getLocation())
                }
            }
        }
end

procedure bar()
    return baz()
end

procedure baz()
    initial U0().throw("First exception")
    U1().throw("Second exception")
end


func factorial(n) {
    if n < 2 {
       1
    } else {
       n * factorial(n - 1)
    }
}


define method factorial (n)
  if (n < 1)
    error("invalid argument");
  else
    reduce1(\*, range(from: 1, to: n))
  end
end method;


Set objShell = CreateObject("WScript.Shell")
objShell.Run "%comspec% /K dir",3,True


Attribute VB_Name = "mdlShellAndWait"
Option Explicit

Private Declare Function OpenProcess Lib "kernel32" _
    (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, _
    ByVal dwProcessId As Long) As Long

Private Declare Function GetExitCodeProcess Lib "kernel32" _
    (ByVal hProcess As Long, lpExitCode As Long) As Long

Private Const STATUS_PENDING = &H103&
Private Const PROCESS_QUERY_INFORMATION = &H400

'
' Little function go get exit code given processId
'
Function ProcessIsRunning( processId as Long ) as Boolean
    Dim exitCode as Long
    Call GetExitCodeProcess(lProcessId, exitCode)
    ProcessIsRunning = (exitCode = STATUS_PENDING)
End Function

' Spawn subprocess and wait for it to complete.
'   I believe that the command in the command line must be an exe or a bat file.
'   Maybe, however, it can reference any file the system knows how to "Open"
'
' commandLine is an executable.
' expectedDuration - is for poping up a dialog for whatever
' infoText - text for progressDialog dialog

Public Function ShellAndWait( commandLine As String, _
    expectedDuration As Integer ) As Boolean

    Dim inst As Long
    Dim startTime As Long
    Dim expirationTime As Long
    Dim pid As Long
    Dim expiresSameDay As Boolean

    On Error GoTo HandleError

    'Deal with timeout being reset at Midnight ($hitForBrains VB folks)
    startTime = CLng(Timer)
    expirationTime = startTime + expectedDuration
    expiresSameDay = expirationTime < 86400
    If Not expiresSameDay Then
        expirationTime = expirationTime - 86400
    End If

    inst = Shell(commandLine, vbMinimizedNoFocus)

    If inst <> 0 Then
        pid = OpenProcess(PROCESS_QUERY_INFORMATION, False, inst)

        Do While ProcessIsRunning( pid)
            DoEvents
            If Timer > expirationTime And (expiresSameDay Or Timer < startTime) Then
                Exit Do
            End If
        Loop
        ShellAndWait = True
    Else
        MsgBox ("Couldn't execute command: " & commandLine)
        ShellAndWait = False
    End If

    Exit Function

HandleError:
    MsgBox ("Couldn't execute command: " & commandLine)
    ShellAndWait = False
End Function

Sub SpawnDir()
   ShellAndWait("dir", 10)
End Sub


Module System_Command

    Sub Main()
        Dim cmd As New Process
        cmd.StartInfo.FileName = "cmd.exe"
        cmd.StartInfo.RedirectStandardInput = True
        cmd.StartInfo.RedirectStandardOutput = True
        cmd.StartInfo.CreateNoWindow = True
        cmd.StartInfo.UseShellExecute = False

        cmd.Start()

        cmd.StandardInput.WriteLine("dir")
        cmd.StandardInput.Flush()
        cmd.StandardInput.Close()

        Console.WriteLine(cmd.StandardOutput.ReadToEnd)
    End Sub

End Module


procedure test;
begin
  raise Exception.Create('Sample Exception');
end;


func Integer.Add(x) {
    throw @NegativesNotAllowed(x) when x < 0
    this + x
}

try {
    12.Add(-5)
} catch {
    @NegativesNotAllowed(x) => print("Negative number: \(x)")
}


procedure Test;
begin
   raise Exception.Create('Sample Exception');
end;


MCSKIP "WITH" NL
"" Fibonacci - recursive
MCSKIP MT,<>
MCINS %.
MCDEF FIB WITHS ()
AS <MCSET T1=%A1.
MCGO L1 UNLESS 2 GR T1
%T1.<>MCGO L0
%L1.%FIB(%T1.-1)+FIB(%T1.-2).>
fib(0) is FIB(0)
fib(1) is FIB(1)
fib(2) is FIB(2)
fib(3) is FIB(3)
fib(4) is FIB(4)
fib(5) is FIB(5)


U0 := Exception clone
U1 := Exception clone

foo := method(
    for(i,1,2,
        try(
            bar(i)
        )catch( U0,
            "foo caught U0" print
        )pass
    )
)
bar := method(n,
    baz(n)
)
baz := method(n,
    if(n == 1,U0,U1) raise("baz with n = #{n}" interpolate)
)

foo


main=: monad define
  smoutput 'main'
  try. foo ''
  catcht. smoutput 'main caught ',type_jthrow_
  end.
)

foo=: monad define
  smoutput '  foo'
  for_i. 0 1 do.
    try. bar i
    catcht. if. type_jthrow_-:'U0' do. smoutput '  foo caught ',type_jthrow_ else. throw. end.
    end.
  end.
)

bar=: baz [ smoutput bind '    bar'

baz=: monad define
  smoutput '      baz'
  type_jthrow_=: 'U',":y throw.
)


class U0 extends Exception { }
class U1 extends Exception { }

public class ExceptionsTest {
    public static void foo() throws U1 {
        for (int i = 0; i <= 1; i++) {
            try {
                bar(i);
            } catch (U0 e) {
                System.out.println("Function foo caught exception U0");
            }
        }
    }

    public static void bar(int i) throws U0, U1 {
        baz(i); // Nest those calls
    }

    public static void baz(int i) throws U0, U1 {
        if (i == 0)
            throw new U0();
        else
            throw new U1();
    }

    public static void main(String[] args) throws U1 {
        foo();
    }
}


factorial:
    1
    while over:
        * over
        swap -- swap
    drop swap


/* run_system_command.wren */
class Command {
    foreign static exec(name, param) // the code for this is provided by Go
}

Command.exec("ls", "-lt")
System.print()
Command.exec("dir", "")


; Executes '/bin/ls'
; Build with:
;   nasm -felf32 execls.asm
;   ld -m elf_i386 execls.o -o execls

global  _start
section .text

_start:
    mov eax, 0x0B       ; sys_execve(char *str, char **args, char **envp)
    mov ebx, .path      ; pathname
    push DWORD 0
    push DWORD .path
    lea ecx, [esp]      ; arguments [pathname]
    xor edx, edx        ; environment variables []
    int 0x80            ; syscall
.path:
    db  '/bin/ls', 0x00


system("dir")
//It will return the exit code of the command; its output (if any) will be lost.

print system$("dir")
//Returns the output as a large string.


System.cmd(System.isWindows and "dir" or "ls")


stuff-going-wrong:
	raise :value-error

try:
	stuff-going-wrong
catch value-error:
	!print "Whoops!"


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]
    }
}


class MyException : Exception
{
    constructor new()
        <= new("MyException raised");
}


MODULE Fibonacci;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;

PROCEDURE Fibonacci(n : LONGINT) : LONGINT;
VAR
    a,b,c : LONGINT;
BEGIN
    IF n<0 THEN RETURN 0 END;

    a:=1;
    b:=1;

    WHILE n>0 DO
        c := a + b;
        a := b;
        b := c;
        DEC(n)
    END;

    RETURN a
END Fibonacci;

VAR
    buf : ARRAY[0..63] OF CHAR;
    i : INTEGER;
    r : LONGINT;
BEGIN
    FOR i:=0 TO 10 DO
        r := Fibonacci(i);

        FormatString("%l\n", buf, r);
        WriteString(buf);
    END;

    ReadChar
END Fibonacci.


function U() {}
U.prototype.toString = function(){return this.className;}

function U0() {
    this.className = arguments.callee.name;
}
U0.prototype = new U();

function U1() {
    this.className = arguments.callee.name;
}
U1.prototype = new U();

function foo() {
    for (var i = 1; i <= 2; i++) {
        try {
            bar();
        }
        catch(e if e instanceof U0) {
            print("caught exception " + e);
        }
    }
}

function bar() {
    baz();
}

function baz() {
    // during the first call, redefine the function for subsequent calls
    baz = function() {throw(new U1());}
    throw(new U0());
}

foo();


# n is assumed to be the number of times baz has been previously called:
def baz(n):
  if n==0 then error("U0")
  elif n==1 then error("U1")
  else "Goodbye"
  end;

def bar(n): baz(n);

def foo:
  (try bar(0) catch if . == "U0" then "We caught U0" else error(.) end),
  (try bar(1) catch if . == "U0" then "We caught U0" else error(.) end);

foo


struct U0 <: Exception end
struct U1 <: Exception end

function foo()
    for i in 1:2
        try
            bar()
        catch err
            if isa(err, U0) println("catched U0")
            else rethrow(err) end
        end
    end
end

function bar()
    baz()
end

function baz()
    if isdefined(:_called) && _called
        throw(U1())
    else
        global _called = true
        throw(U0())
    end
end

foo()


// version 1.0.6

class U0 : Throwable("U0 occurred")
class U1 : Throwable("U1 occurred")

fun foo() {
    for (i in 1..2) {
        try {
            bar(i)
        } catch(e: U0) {
            println(e.message)
        }
    }
}

fun bar(i: Int) {
    baz(i)
}

fun baz(i: Int) {
    when (i) {
        1 -> throw U0()
        2 -> throw U1()
    }
}

fun main(args: Array<String>) {
    foo()
}


pragma.enable("accumulator")
def factorial(n) {
  return accum 1 for i in 2..n { _ * i }
}


-module( exceptions ).

-export( [task/0] ).

task() ->
    try
    erlang:throw( new_exception )

    catch
    _:Exception -> io:fwrite( "Catched ~p~n", [Exception] )

    end.


"Install Linux, Problem Solved" throw

TUPLE: velociraptor ;
\ velociraptor new throw


# define custom exception class
# StandardError is base class for all exception classes
class MyError : StandardError {
  def initialize: message {
    # forward to StdError's initialize method
    super initialize: message
  }
}

try {
  # raises/throws a new MyError exception within try-block
  MyError new: "my message" . raise!
} catch MyError => e {
  # catch exception
  # this will print "my message"
  e message println
} finally {
  # this will always be executed (as in e.g. Java)
  "This is how exception handling in Fancy works :)" println
}


PROCEDURE Fib(n: INTEGER): INTEGER =
  BEGIN
    IF n < 2 THEN
      RETURN n;
    ELSE
      RETURN Fib(n-1) + Fib(n-2);
    END;
  END Fib;


val .U0 = h{"msg": "U0"}
val .U1 = h{"msg": "U1"}

val .baz = f(.i) throw if(.i==0: .U0; .U1)
val .bar = f(.i) .baz(.i)

val .foo = f() {
    for .i in [0, 1] {
        .bar(.i)
        catch if _err["msg"] == .U0["msg"] {
            writeln "caught .U0 in .foo()"
        } else {
            throw
        }
    }
}

.foo()


define try(exception) => {
    local(
        gb = givenblock,
        error
    )
    handle => {
        // Only relay error if it's not the specified exception
        if(#error) => {
            if(#error->get(2) == #exception) => {
                stdoutnl('Handled exception: '+#error->get(2))
            else
                stdoutnl('Throwing exception: '+#error->get(2))
                fail(:#error)
            }
        }
    }
    protect => {
        handle_error => {
            #error = (:error_code,error_msg,error_stack)
        }
        #gb()
    }
}

define foo => {
    stdoutnl('foo')
    try('U0') => { bar }
    try('U0') => { bar }
}

define bar => {
    stdoutnl('- bar')
    baz()
}

define baz => {
    stdoutnl('  - baz')
    var(bazzed) ? fail('U1') | $bazzed = true
    fail('U0')
}


local baz_counter=1
function baz()
  if baz_counter==1 then
    baz_counter=baz_counter+1
    error("U0",3)--3 sends it down the call stack.
  elseif baz_counter==2 then
    error("U1",3)--3 sends it down the call stack.
  end
end

function bar()
  baz()
end

function foo()
  function callbar()
    local no_err,result = pcall(bar)
    --pcall is a protected call which catches errors.
    if not no_err then
      --If there are no errors, pcall returns true.
      if not result:match("U0") then
        --If the error is not a U0 error, rethrow it.
        error(result,2)
        --2 is the distance down the call stack to send
        --the error. We want it to go back to the callbar() call.
      end
    end
  end
  callbar()
  callbar()
end

foo()


num_times:=0:
baz := proc()
    global num_times := num_times + 1;
    error `if`(num_times <= 1, "U0", "U1");
end proc:

bar:=proc()
    baz();
end proc;

foo:=proc()
    local i;
    for i from 0 to 1 do
        bar();
    end do;
end proc;


foo[] := Catch[ bar[1]; bar[2]; ]

bar[i_] := baz[i];

baz[i_] := Switch[i,
  1, Throw["Exception U0 in baz"];,
  2, Throw["Exception U1 in baz"];]


func factorial n . r .
  r = 1
  i = 2
  while i <= n
    r = r * i
    i += 1
  .
.
call factorial 7 r
print r


(define (fact n)
    (for/product ((f (in-range 2 (1+ n)))) f))
(fact 10)
    → 3628800


// Create a new error class by subclassing sys::Err
const class SpecialErr : Err
{
  // you must provide some message about the error
  // to the parent class, for reporting
  new make () : super ("special error") {}
}

class Main
{
  static Void fn ()
  {
    throw SpecialErr ()
  }

  public static Void main ()
  {
    try
      fn()
    catch (SpecialErr e)
      echo ("Caught " + e)
  }
}


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


' FB 1.05.0 Win64

Enum ErrorType
  myError = 1000
End Enum

Sub foo()
  Err = 1000 ' raise a user-defined error
End Sub

Sub callFoo()
  foo()
  Dim As Long errNo = Err ' cache Err in case it's reset by a different function
  Select Case errNo
    Case 0
      ' No error (system defined)
    Case 1 To 17
      ' System defined runtime errors
    Case myError:   ' catch myError
      Print "Caught myError : Error number"; errNo
    Case Else
      ' catch any other type of errors here
  End Select
  ' add any clean-up code here
End Sub

callfoo()
Print
Print "Press any key to quit"
Sleep


# Main
Lei ha clacsonato
voglio un nonnulla, Necchi mi porga un nonnulla
il nonnulla come se fosse brematurata la supercazzola bonaccia con il nonnulla o scherziamo?
un nonnulla a posterdati

# Fibonacci function 'bonaccia'
blinda la supercazzola Necchi bonaccia con antani Necchi o scherziamo? che cos'è l'antani?
minore di 3: vaffanzum 1! o tarapia tapioco: voglio unchiamo, Necchi come se fosse brematurata
la supercazzola bonaccia con antani meno 1 o scherziamo? voglio duechiamo,
Necchi come se fosse brematurata la supercazzola bonaccia con antani meno 2 o scherziamo? vaffanzum
unchiamo più duechiamo! e velocità di esecuzione


function exceptionsCatchNestedCall()
    function foo()

        try
            bar(1);
            bar(2);
        catch
            disp(lasterror);
            rethrow(lasterror);
        end

    end

    function bar(i)
        baz(i);
    end

    function baz(i)
        switch i
            case 1
                error('BAZ:U0','HAHAHAH');
            case 2
                error('BAZ:U1','AWWWW');
            otherwise
                disp 'I can''t do that Dave.';
        end
    end

    foo();

end


using System;
using System.Console;

namespace NestedExceptions
{
    public class U0 : Exception
    {
        public this() {base()}
    }

    public class U1 : Exception
    {
        public this() {base()}
    }

    module NestedExceptions
    {
        Foo () : void
        {
            mutable call = 0;

            repeat(2) {
                try {
                    Bar(call);
                }
                catch {
                    |e is U0 => WriteLine("Exception U0 caught.")
                }
                finally {
                    call++;
                }
            }
        }

        Bar (call : int) : void
        {
            Baz(call)
        }

        Baz (call : int) : void // throw U0() on first call, U1() on second
        {
            unless (call > 0) throw U0();
            when (call > 0) throw U1();
        }

        Main () : void
        {
            Foo()
        }
    }
}


type U0 = object of Exception
type U1 = object of Exception

proc baz(i) =
  if i > 0: raise newException(U1, "Some error")
  else: raise newException(U0, "Another error")

proc bar(i) =
  baz(i)

proc foo() =
  for i in 0..1:
    try:
      bar(i)
    except U0:
      echo "Function foo caught exception U0"

foo()


@interface U0 : NSObject { }
@end
@interface U1 : NSObject { }
@end
@implementation U0
@end
@implementation U1
@end

void foo();
void bar(int i);
void baz(int i);

void foo() {
  for (int i = 0; i <= 1; i++) {
    @try {
      bar(i);
    } @catch (U0 *e) {
      NSLog(@"Function foo caught exception U0");
    }
  }
}

void bar(int i) {
  baz(i); // Nest those calls
}

void baz(int i) {
  if (i == 0)
    @throw [U0 new];
  else
    @throw [U1 new];
}

int main (int argc, const char * argv[]) {
  @autoreleasepool {

    foo();

  }
  return 0;
}


function fact(n int in) returns (bigint)
    if (n < 0)
        writestdout("No negative numbers");
        return (0);
    end
    ans bigint = 1;
    for (i int from 1 to n)
        ans *= i;
    end
    return (ans);
end


note
	description: "recursive and iterative factorial example of a positive integer."

class
	FACTORIAL_EXAMPLE

create
	make

feature -- Initialization

	make
		local
			n: NATURAL
		do
			n := 5
			print ("%NFactorial of " + n.out + " = ")
			print (recursive_factorial (n))
		end

feature -- Access

	recursive_factorial (n: NATURAL): NATURAL
			-- factorial of 'n'
		do
			if n = 0 then
				Result := 1
			else
				Result := n * recursive_factorial (n - 1)
			end
		end

	iterative_factorial (n: NATURAL): NATURAL
			-- factorial of 'n'
		local
			v: like n
		do
			from
				Result := 1
				v := n
			until
				v <= 1
			loop
				Result := Result * v
				v := v - 1
			end
		end

end


Public Sub Main()
Dim iInteger As Integer

MakeError
DivError

iInteger = "2.54"

Catch
  Print Error.Text

End
'______________________
Public Sub DivError()

Print 10 / 0

Catch
  Print Error.Text

End
'______________________
Public Sub MakeError()

Error.Raise("My Error")

Catch
  Print Error.Text

End


package main

import "fmt"

func foo() int {
	fmt.Println("let's foo...")
	defer func() {
		if e := recover(); e != nil {
			fmt.Println("Recovered from", e)
		}
	}()
	var a []int
	a[12] = 0
	fmt.Println("there's no point in going on.")
	panic("never reached")
	panic(fmt.Scan) // Can use any value, here a function!
}

func main() {
	foo()
	fmt.Println("glad that's over.")
}


0 VAR a .
1 VAR b .
INPUT TOINT
FOR :
    a b + VAR c .
    a PRINT .
    b VAR a .
    c VAR b .
ENDFOR


exception U0
exception U1

let baz i =
  raise (if i = 0 then U0 else U1)

let bar i = baz i (* Nest those calls *)

let foo () =
  for i = 0 to 1 do
    try
      bar i
    with U0 ->
      print_endline "Function foo caught exception U0"
  done

let () = foo ()


Exception Class new: U0
Exception Class new: U1

: baz  ifZero: [ "First call" U0 throw ] else: [ "Second call" U1 throw ] ;
: bar  baz ;

: foo
| e |
   try: e [ 0 bar ] when: [ e isKindOf(U0) ifTrue: [ "Catched" .cr ] else: [ e throw ] ]
   try: e [ 1 bar ] when: [ e isKindOf(U0) ifTrue: [ "Catched" .cr ] else: [ e throw ] ]
   "Done" . ;


declare
  proc {Foo}
     for I in 1..2 do
        try
           {Bar I}
        catch u0 then {System.showInfo "Procedure Foo caught exception u0"}
        end
     end
  end

  proc {Bar I} {Baz I} end

  proc {Baz I}
     if I == 1 then
        raise u0 end
     else
        raise u1 end
     end
  end
in
  {Foo}


call = 0;

U0() = error("x = ", 1, " should not happen!");
U1() = error("x = ", 2, " should not happen!");
baz(x) = if(x==1, U0(), x==2, U1());x;
bar() = baz(call++);
foo() = if(!call, iferr(bar(), E, printf("Caught exception, call=%d",call)), bar())


fact = fact' 1L
       where fact' acc 0 = acc
             fact' acc n = fact' (n * acc) (n - 1)


defmodule Factorial do
  # Simple recursive function
  def fac(0), do: 1
  def fac(n) when n > 0, do: n * fac(n - 1)

  # Tail recursive function
  def fac_tail(0), do: 1
  def fac_tail(n), do: fac_tail(n, 1)
  def fac_tail(1, acc), do: acc
  def fac_tail(n, acc) when n > 1, do: fac_tail(n - 1, acc * n)

  # Tail recursive function with default parameter
  def fac_default(n, acc \\ 1)
  def fac_default(0, acc), do: acc
  def fac_default(n, acc) when n > 0, do: fac_default(n - 1, acc * n)

  # Using Enumeration features
  def fac_reduce(0), do: 1
  def fac_reduce(n) when n > 0, do: Enum.reduce(1..n, 1, &*/2)

  # Using Enumeration features with pipe operator
  def fac_pipe(0), do: 1
  def fac_pipe(n) when n > 0, do: 1..n |> Enum.reduce(1, &*/2)

end


try {
  U8 *err = 'Error';
  throw(err); // throw exception
} catch {
  if (err == 'Error')
    Print("Raised 'Error'");
  PutExcept; // print the exception and stack trace
}


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


FIBOITER(N)
 ;Iterative version to get the Nth Fibonacci number
 ;N must be a positive integer
 ;F is the tree containing the values
 ;I is a loop variable.
 QUIT:(N\1'=N)!(N<0) "Error: "_N_" is not a positive integer."
 NEW F,I
 SET F(0)=0,F(1)=1
 QUIT:N<2 F(N)
 FOR I=2:1:N SET F(I)=F(I-1)+F(I-2)
 QUIT F(N)


sub foo {
    foreach (0..1) {
        eval { bar($_) };
        if ([email protected] =~ /U0/) { print "Function foo caught exception U0\n"; }
        else { die; } # propagate the exception
    }
}

sub bar {
    baz(@_); # Nest those calls
}

sub baz {
    my $i = shift;
    die ($i ? "U1" : "U0");
}

foo();


constant U0 = 0,
         U1 = 1

integer count = 0

procedure baz()
    count += 1
    if count=1 then
        throw(U0,{{"any",{{"thing"},"you"}},"like"})
    else
        throw(U1)
    end if
end procedure

procedure bar()
    baz()
end procedure

procedure foo()
    for i=1 to 2 do
        try
            bar()
        catch e
            if e[E_CODE]=U0 then
                ?e[E_USER]
            else
                throw(e)    -- (terminates)
            end if
        end try
        puts(1,"still running...\n")
    end for
    puts(1,"not still running...\n")
end procedure

foo()


factorial : Int -> Int
factorial n =
  if n < 1 then 1 else n*factorial(n-1)


;; Functional (most elegant and best suited to Lisp dialects):
(defun fact (n)
  "Return the factorial of integer N, which require to be positive or 0."
  ;; Elisp won't do any type checking automatically, so
  ;; good practice would be doing that ourselves:
  (if (not (and (integerp n) (>= n 0)))
      (error "Function fact (N): Not a natural number or 0: %S" n))
  ;; But the actual code is very short:
  (apply '* (number-sequence 1 n)))
  ;; (For N = 0, number-sequence returns the empty list, resp. nil,
  ;; and the * function works with zero arguments, returning 1.)


   pickyPicky =: verb define
     if. y-:'bad argument' do.
        throw.
     else.
        'thanks!'
     end.
   )

   tryThis  =: verb define
     try.
        pickyPicky y
     catcht.
        'Uh oh!'
     end.
   )

   tryThis 'bad argument'
Uh oh!


//Checked exception
public class MyException extends Exception {
   //Put specific info in here
}

//Unchecked exception
public class MyRuntimeException extends RuntimeException {}


function doStuff() {
  throw new Error('Not implemented!');
}


def fibIter(n)
        if (n < 2)
                return n
        end if

        $fib = 1
        $fibPrev = 1

	for num in range(2, n - 1)
                fib += fibPrev
                fibPrev = fib - fibPrev
        end for

        return fib
end


(de foo ()
   (for Tag '(U0 U1)
      (catch 'U0
         (bar Tag) ) ) )

(de bar (Tag)
   (baz Tag) )

(de baz (Tag)
   (throw Tag) )

(mapc trace '(foo bar baz))
(foo)


/* Exceptions: Catch an exception thrown in a nested call */
test: proc options (main);
                                                   /* 8/1/2011 */
   declare (m, n) fixed initial (2);
   declare (U0, U1) condition;

foo: procedure () returns (fixed);
   on condition(U0) snap begin;
      put list ('Raised condition U0 in function <bar>.'); put skip;
   end;
   m = bar();
   m = bar();
   return (m);
end foo;

bar: procedure () returns (fixed);
   n = n + 1;
   return (baz());
   return (n);
end bar;
baz: procedure () returns (fixed);
   declare first bit(1) static initial ('1'b);
   n = n + 1;
   if first then do; first = '0'b; signal condition(U0); end;
   else signal condition(U1);
   return (n);
end baz;

   m = foo();
end test;


class U0(Exception): pass
class U1(Exception): pass

def foo():
    for i in range(2):
        try:
            bar(i)
        except U0:
            print("Function foo caught exception U0")

def bar(i):
    baz(i) # Nest those calls

def baz(i):
    raise U1 if i else U0

foo()


  [ this ] is U0

  [ this ] is U1

  [ 0 = iff U0 else U1
    message put bail ] is baz ( n --> )

  [ baz ]              is bar ( n --> )

  [ 2 times
      [ i^
        1 backup
        bar
        bailed if
          [ message share
            U0 oats iff
              [ say "Exception U0 raised." cr
                echostack
                $ "Press enter to continue"
                input drop
                message release
                drop ]
              else [ drop bail ] ] ] ] is foo


number_of_calls_to_baz <- 0

foo <- function()
{
   for(i in 1:2) tryCatch(bar())
}

bar <- function() baz()

baz <- function()
{
   e <- simpleError(ifelse(number_of_calls_to_baz > 0, "U1", "U0"))
   assign("number_of_calls_to_baz", number_of_calls_to_baz + 1, envir=globalenv())
   stop(e)
}


#lang racket

(define-struct (exn:U0 exn) ())
(define-struct (exn:U1 exn) ())

(define (foo)
  (for ([i 2])
    (with-handlers ([exn:U0? (λ(_) (displayln "Function foo caught exception U0"))])
      (bar i))))

(define (bar i)
  (baz i))

(define (baz i)
  (if (= i 0)
      (raise (make-exn:U0 "failed 0" (current-continuation-marks)))
      (raise (make-exn:U1 "failed 1" (current-continuation-marks)))))

(foo)


long factorial(int n) {
    long result = 1;
    do {
        result *= n;
    while(--n);
    return result;
}


lists:foldl(fun(X,Y) -> X*Y end, 1, lists:seq(1,N)).


function extendedsqrt(x)
    try sqrt(x)
    catch
        if x isa Number
            sqrt(complex(x, 0))
        else
            throw(DomainError())
        end
    end
end

@show extendedsqrt(1)   # 1
@show extendedsqrt(-1)  # 0.0 + 1.0im
@show extendedsqrt('x') # ERROR: DomainError


// version 1.0.6

// In Kotlin all Exception classes derive from Throwable and, by convention, end with the word 'Exception'
class MyException (override val message: String?): Throwable(message)

fun foo() {
    throw MyException("Bad foo!")
}

fun goo() {
    try {
        foo()
    }
    catch (me: MyException) {
        println("Caught MyException due to '${me.message}'")
        println("\nThe stack trace is:\n")
        me.printStackTrace()
    }
}

fun main(args: Array<String>) {
    goo()
}


using System;
using System.Console;

module Fibonacci
{
    Fibonacci(x : long) : long
    {
        |x when x < 2 => x
        |_ => Fibonacci(x - 1) + Fibonacci(x - 2)
    }

    Main() : void
    {
        def num = Int64.Parse(ReadLine());
        foreach (n in $[0 .. num])
            WriteLine("{0}: {1}", n, Fibonacci(n));
    }
}


sub foo() {
    for 0..1 -> $i {
        bar $i;
        CATCH {
            when /U0/ { say "Function foo caught exception U0" }
        }
    }
}

sub bar($i) { baz $i }

sub baz($i) { die "U$i" }

foo;


/*REXX program  creates  two exceptions and demonstrates how to  handle  (catch)  them. */
call foo                                         /*invoke the  FOO  function  (below).  */
say 'The REXX mainline program has completed.'   /*indicate that Elroy was here.        */
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
foo:   call bar;   call bar                      /*invoke  BAR  function  twice.        */
       return 0                                  /*return a zero to the invoker.        */
                                                 /*the 1st  U0  in REXX program is used.*/
U0:    say 'exception U0 caught in FOO'          /*handle the  U0  exception.           */
       return -2                                 /*return to the invoker.               */
/*──────────────────────────────────────────────────────────────────────────────────────*/
bar:   call baz                                  /*have BAR function invoke BAZ function*/
       return 0                                  /*return a zero to the invoker.        */
/*──────────────────────────────────────────────────────────────────────────────────────*/
baz:   if symbol('BAZ#')=='LIT'  then baz#=0     /*initialize the first BAZ invocation #*/
       baz# = baz#+1                             /*bump the BAZ invocation number by 1. */
       if baz#==1  then signal U0                /*if first  invocation, then raise  U0 */
       if baz#==2  then signal U1                /* " second      "        "    "    U1 */
       return 0                                  /*return a   0  (zero)  to the invoker.*/
                                                 /* [↓]  this  U0 subroutine is ignored.*/
U0:    return -1                                 /*handle exception if not caught.      */
U1:    return -1                                 /*   "       "      "  "     "         */


def foo
  2.times do |i|
    begin
      bar(i)
    rescue U0
      $stderr.puts "captured exception U0"
    end
  end
end

def bar(i)
  baz(i)
end

def baz(i)
  raise i == 0 ? U0 : U1
end

class U0 < StandardError; end

class U1 < StandardError; end

foo


#[derive(Debug)]
enum U {
    U0(i32),
    U1(String),
}

fn baz(i: u8) -> Result<(), U> {
    match i {
        0 => Err(U::U0(42)),
        1 => Err(U::U1("This will be returned from main".into())),
        _ => Ok(()),
    }
}

fn bar(i: u8) -> Result<(), U> {
    baz(i)
}

fn foo() -> Result<(), U> {
    for i in 0..2 {
        match bar(i) {
            Ok(()) => {},
            Err(U::U0(n)) => eprintln!("Caught U0 in foo: {}", n),
            Err(e) => return Err(e),
        }
    }
    Ok(())
}

fn main() -> Result<(), U> {
    foo()
}


    PROCEDURE FACTORIAL(X%->F)
      F=1
      IF X%<>0 THEN
        FOR I%=X% TO 2 STEP Ä1 DO
          F=F*X%
        END FOR
      END IF
    END PROCEDURE


function factorial(integer n)
  atom f = 1
  while n > 1 do
    f *= n
    n -= 1
  end while

  return f
end function


# do something
throw "not a math exception"

catch .e {
    if .e["cat"] == "math" {
        # change result...
    } else {
        # rethrow the exception
        throw
    }
} else {
    # no exception
    ...
}


protect => {
   handle_error => {
        // do something else
   }
   fail(-1,'Oops')
}


-- parent script "ErrorHandler"

on alertHook (me, errorType, errorMessage, alertType)
  if alertType=#alert then return 0 -- ignore programmatic alerts

  -- log error in file "error.log"
  fn = _movie.path&"error.log"
  fp = xtra("fileIO").new()
  fp.openFile(fn, 2)
  if fp.status() = -37 then
    fp.createFile(fn)
    fp.openFile(fn, 2)
  end if
  fp.setPosition(fp.getLength())
  fp.writeString(_system.date() && _system.time() && errorType & ": " & errorMessage & RETURN)
  fp.closeFile()

  return 1 -- continues movie playback, no error dialog
end


to div.checked :a :b
  if :b = 0 [(throw "divzero 0)]
  output :a / :b
end
to div.safely :a :b
  output catch "divzero [div.checked :a :b]
end


function fib(n) = if n < 2 then n else fib(n - 2) + fib(n - 1);


object ExceptionsTest extends App {
  class U0 extends Exception
  class U1 extends Exception

  def foo {
    for (i <- 0 to 1)
      try {
        bar(i)
      } catch { case e: U0 => println("Function foo caught exception U0") }
  }

  def bar(i: Int) {
    def baz(i: Int) = { if (i == 0) throw new U0 else throw new U1 }

    baz(i) // Nest those calls
  }

  foo
}


$ include "seed7_05.s7i";

const EXCEPTION: U0 is enumlit;
const EXCEPTION: U1 is enumlit;

const proc: baz (in integer: num) is func
  begin
    if num = 1 then
      raise U0;
    else
      raise U1;
    end if;
  end func;

const proc: bar (in integer: num) is func
  begin
    baz(num);
  end func;

const proc: foo is func
  local
    var integer: num is 0;
  begin
    for num range 1 to 2 do
      block
        bar(num);
      exception
        catch U0: writeln("U0 catched");
      end block;
    end for;
  end func;

const proc: main is func
  begin
    foo;
  end func;


func baz(i) { die "U#{i}" };
func bar(i) { baz(i)      };

func foo {
    [0, 1].each { |i|
        try   { bar(i) }
        catch { |_, msg|
            msg ~~ /^U0/ ? say "Function foo() caught exception U0"
                         : die msg;       # re-raise the exception
        };
    }
}

foo();


Exception subclass: #U0.
Exception subclass: #U1.

Object subclass: Foo [

    bazCount := 0.

    foo
        [2 timesRepeat:
            [ "==>" [self bar] "<=="
                on: U0
                do:
                    [:sig |
                    'Call to bar was aborted by exception U0' printNl.
                    sig return]]]

    bar
        [self baz]

    baz
        [bazCount := bazCount + 1.
        bazCount = 1 ifTrue: [U0 new signal].
        bazCount = 2 ifTrue: [U1 new signal].
        "Thirds time's a charm..."]
]


நிரல்பாகம்  fact ( n )
  @( n == 0 ) ஆனால்
            பின்கொடு  1
     இல்லை
            பின்கொடு    n*fact( n - 1 )
    முடி
முடி

பதிப்பி fact ( 10 )


:- 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.


/* NetRexx */

options replace format comments java crossref savelog symbols

numeric digits 210000                  /*prepare for some big 'uns.     */
parse arg x y .                        /*allow a single number or range.*/
if x == '' then do                     /*no input? Then assume -30-->+30*/
  x = -30
  y = -x
  end

if y == '' then y = x             /*if only one number, show fib(n)*/
loop k = x to y                   /*process each Fibonacci request.*/
  q = fib(k)
  w = q.length                    /*if wider than 25 bytes, tell it*/
  say 'Fibonacci' k"="q
  if w > 25 then say 'Fibonacci' k "has a length of" w
  end k
exit

/*-------------------------------------FIB subroutine (non-recursive)---*/
method fib(arg) private static
  parse arg n
  na = n.abs

  if na < 2 then return na             /*handle special cases.          */
  a = 0
  b = 1

  loop j = 2 to na
    s = a + b
    a = b
    b = s
    end j

  if n > 0 | na // 2 == 1 then return  s /*if positive or odd negative... */
                          else return -s /*return a negative Fib number.  */


enum MyException : ErrorType {
  case U0
  case U1
}

func foo() throws {
  for i in 0 ... 1 {
    do {
      try bar(i)
    } catch MyException.U0 {
      print("Function foo caught exception U0")
    }
  }
}

func bar(i: Int) throws {
  try baz(i) // Nest those calls
}

func baz(i: Int) throws {
  if i == 0 {
    throw MyException.U0
  } else {
    throw MyException.U1
  }
}

try foo()


package require Tcl 8.5

proc foo {} {
    set code [catch {bar} ex options]
    if {$code == 1} {
        switch -exact -- $ex {
            U0      {puts "caught exception U0"}
            default {return -options $options $ex ;# re-raise exception}
        }
    }
}

proc bar {} {baz}

# create an alias to pass the initial exception U0 to the baz proc
interp alias {} baz {} _baz U0

proc _baz {exception} {
    # re-set the alias so subsequent invocations will use exception U1
    interp alias {} baz {} _baz U1
    # throw
    return -code error $exception
}

foo
foo


@(defex u0)
@(defex u1)
@(define baz (x))
@  (cases)
@    (bind x "0")
@    (throw u0 "text0")
@  (or)
@    (bind x "1")
@    (throw u1 "text1")
@  (end)
@(end)
@(define bar (x))
@  (baz x)
@(end)
@(define foo ())
@  (next :list @'("0" "1"))
@  (collect)
@num
@    (try)
@      (bar num)
@    (catch u0 (arg))
@      (output)
caught u0: @arg
@      (end)
@    (end)
@  (end)
@(end)
@(foo)


#import std

baz =

~&?(
   ~&h?(
      :/'baz succeeded with this input:',
      <'baz threw a user-defined empty string exception','U1'>!%),
   <'baz threw a user-defined empty file exception','U0'>!%)

bar = :/'bar received this result from normal termination of baz:'+ baz

#executable&

foo =

guard(
   :/'foo received this result from normal termination of bar:'+ bar,
   'U0'?=z/~& :/'foo caught an exception with this error message:')


Class U0
    Inherits Exception
End Class

Class U1
    Inherits Exception
End Class

Module Program
    Sub Main()
        Foo()
    End Sub

    Sub Foo()
        Try
            Bar()
            Bar()
        Catch ex As U0
            Console.WriteLine(ex.GetType.Name & " caught.")
        End Try
    End Sub

    Sub Bar()
        Baz()
    End Sub

    Sub Baz()
        ' Static local variable is persisted between calls of the method and is initialized only once.
        Static firstCall As Boolean = True
        If firstCall Then
            firstCall = False
            Throw New U0()
        Else
            Throw New U1()
        End If
    End Sub
End Module


//val inline factorial :
//   ^a ->  ^a
//    when  ^a : (static member get_One : ->  ^a) and
//          ^a : (static member ( + ) :  ^a *  ^a ->  ^a) and
//          ^a : (static member ( * ) :  ^a *  ^a ->  ^a)
let inline factorial n = Seq.reduce (*) [ LanguagePrimitives.GenericOne .. n ]


Module Errors {
      Module Check {
            Module Error1 {
                  A=1/0
            }

            Try ok {
                  Error1
            }
            ' we get an Error, and Error$ print division by zero in module Error1
            If Error or not ok then Print Error$
            Error "New Error"
      }
      Try {
            Check
      }
      Print Error=0  ' no Error return
      Print Error$  ' but Error message isn't clear
      ' Error$ used one time, then cleared automatic
}
Errors
Print Error$=""


errorproc:=proc(n)
local a;
try
a:=1/n;
catch "numeric exception: division by zero":
error "Something went wrong when dividing."
end try;
end proc;


f[x_] := If[x > 10, Throw[overflow], x!]

Example usage :
Catch[f[2] + f[11]]
-> overflow

Catch[f[2] + f[3]]
-> 8


(define (fibonacci n)
    (let (L '(0 1))
        (dotimes (i n)
            (setq L (list (L 1) (apply + L))))
        (L 1)) )


var U0 = "U0"
var U1 = "U1"

var bazCalled = 0

var baz = Fn.new {
    bazCalled = bazCalled + 1
    Fiber.abort( (bazCalled == 1) ? U0 : U1 )
}

var bar = Fn.new {
    baz.call()
}

var foo = Fn.new {
    for (i in 1..2) {
        var f = Fiber.new { bar.call() }
        f.try()
        var err = f.error
        if (err == U0) {
            System.print("Caught exception %(err)")
        } else if (err == U1) {
            Fiber.abort("Uncaught exception %(err) rethrown") // re-throw
        }
    }
}

foo.call()


class U0(Exception.Exception){fcn init{Exception.init("U0")}}
class U1(Exception.Exception){fcn init{Exception.init("U1")}}

fcn foo{try{bar(U0)}catch(U0){} bar(U1)}
fcn bar(e){baz(e)}
fcn baz(e){throw(e)}
foo()


USING: math.ranges sequences ;

: factorial ( n -- n ) [1,b] product ;


EXCEPTION EndOfFile;
EXCEPTION Error(TEXT);


try
      invalid "this statement will fail"
catch e
      println "caught an exception"
      println e
end try


F fib(n:Int) {
	n < 2 returns n
	local a = 1, b = 1
	# i is automatically local because of for()
	for(i=2; i<n; i=i+1) {
		local next = a + b
		a = b
		b = next
	}
	b
}


def class Number {
  def factorial {
    1 upto: self . product
  }
}

# print first ten factorials
1 upto: 10 do_each: |i| {
  i to_s ++ "! = " ++ (i factorial) println
}


class Main
{
  static Int factorialRecursive (Int n)
  {
    if (n <= 1)
      return 1
    else
      return n * (factorialRecursive (n - 1))
  }

  static Int factorialIterative (Int n)
  {
    Int product := 1
    for (Int i := 2; i <=n ; ++i)
    {
      product *= i
    }
    return product
  }

  static Int factorialFunctional (Int n)
  {
    (1..n).toList.reduce(1) |a,v|
    {
      v->mult(a) // use a dynamic invoke
      // alternatively, cast a:  v * (Int)a
    }
  }

  public static Void main ()
  {
    echo (factorialRecursive(20))
    echo (factorialIterative(20))
    echo (factorialFunctional(20))
  }
}


// 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
}


fibi is op n {
  if n<2 then
    n
  else
    x1:=0; x2:=1;
    for i with tell (n - 1) do
      x:=x1+x2;
      x1:=x2;
      x2:=x;
    endfor;
    x2
  endif};


@interface MyException : NSException {
  //Put specific info in here
}
@end


exception My_Exception;;
exception Another_Exception of string;;


: iwillThrowAnException  "A new exception" Exception throw ;

: iwillCatch
| e |
   try: e [ iwillThrowAnException ] when: [ "Exception catched :" . e .cr ]
   try: e [ 1 2 over last ] when: [ "Exception catched :" . e .cr ]
   "Done" println ;


raise sillyError end
raise slightlyLessSilly(data:42 reason:outOfMemory) end


proc Fibonacci(n: int): int64 =
  var fn = float64(n)
  var p: float64 = (1.0 + sqrt(5.0)) / 2.0
  var q: float64 = 1.0 / p
  return int64((pow(p, fn) + pow(q, fn)) / sqrt(5.0))


: fac ( n -- n! ) 1 swap 1+ 1 ?do i * loop ;


trap(/* specific error can be given here, or leave blank to catch all */,
  "caught"
,
  error("bad stuff")
)


# throw an exception
die "Danger, danger, Will Robinson!";

# catch an exception and show it
eval {
    die "this could go wrong mightily";
};
print [email protected] if [email protected];

# rethrow
die [email protected];


fibonacci = n:
    if n <= 1 then n else (fibonacci (n - 1) + fibonacci (n - 2));


throw("oh no")
throw(1)
throw(501,{"she",made[me],Do(it)})


module exceptions;

extern printf;

struct @MyException : @Exception {

};

@Void func throws ex [
	throw new @MyException;
]

@Integer main [
	try func();
	catch (e) {
		if (e::getType == "MyException") {
			printf("MyException thrown!\n");
		} else {
			printf("Unhandled exception!\n");
		}
	}
	return 0;
]


class MyException extends Exception
{
    //  Custom exception attributes & methods
}


(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


MODULE Fibonacci;
IMPORT
  Out := NPCT:Console;

PROCEDURE Fibs(VAR r: ARRAY OF LONGREAL);
VAR
  i: LONGINT;
BEGIN
  r[0] := 1.0; r[1] := 1.0;
  FOR i := 2 TO LEN(r) - 1 DO
    r[i] := r[i - 2] + r[i - 1];
  END
END Fibs;

PROCEDURE FibsR(n: LONGREAL): LONGREAL;
BEGIN
  IF n < 2. THEN
    RETURN n
  ELSE
    RETURN FibsR(n - 1) + FibsR(n - 2)
  END
END FibsR;

PROCEDURE Show(r: ARRAY OF LONGREAL);
VAR
  i: LONGINT;
BEGIN
  Out.String("First ");Out.Int(LEN(r),0);Out.String(" Fibonacci numbers");Out.Ln;
  FOR i := 0 TO LEN(r) - 1 DO
    Out.LongRealFix(r[i],8,0)
  END;
  Out.Ln
END Show;

PROCEDURE Gen(s: LONGINT);
VAR
  x: POINTER TO ARRAY OF LONGREAL;
BEGIN
  NEW(x,s);
  Fibs(x^);
  Show(x^)
END Gen;

PROCEDURE GenR(s: LONGINT);
VAR
  i: LONGINT;
BEGIN
  Out.String("First ");Out.Int(s,0);Out.String(" Fibonacci numbers (Recursive)");Out.Ln;
  FOR i := 1 TO s DO
    Out.LongRealFix(FibsR(i),8,0)
  END;
  Out.Ln
END GenR;

BEGIN
  Gen(10);
  Gen(20);
  GenR(10);
  GenR(20);
END Fibonacci.


' FB 1.05.0 Win64

Function Factorial_Iterative(n As Integer) As Integer
  Var result = 1
  For i As Integer = 2 To n
    result *= i
  Next
  Return result
End Function

Function Factorial_Recursive(n As Integer) As Integer
  If n = 0 Then Return 1
  Return n * Factorial_Recursive(n - 1)
End Function

For i As Integer = 1 To 5
  Print i; " =>"; Factorial_Iterative(i)
Next

For i As Integer = 6 To 10
  Print Using "##"; i;
  Print " =>"; Factorial_Recursive(i)
Next

Print
Print "Press any key to quit"
Sleep


/* Define a new exception, called "my_condition". */
on condition (my_condition) snap begin;
   put skip list ('My condition raised.');
end;

/* Raise that exception */
signal condition (my_condition);

/* Raising that exception causes the message "My condition raised" */
/* to be printed, and execution then resumes at the statement      */
/* following the SIGNAL statement.                                 */


BEGIN
   raise exception 'this is a generic user exception';
   raise exception division_by_zero;
END;


define throw_exception();
   throw([my_exception my_data]);
enddefine;


bundle Default {
  class Fib {
    function : Main(args : String[]), Nil {
      for(i := 0; i <= 10; i += 1;) {
        Fib(i)->PrintLine();
      };
    }

    function : native : Fib(n : Int), Int {
      if(n < 2) {
        return n;
      };

      return Fib(n-1) + Fib(n-2);
    }
  }
}


function factorial
	set x $argv[1]
	set result 1
	for i in (seq $x)
		set result (expr $i '*' $result)
	end
	echo $result
end


// Calculate factorial with math operator
x = 5
println[x!]

// Calculate factorial with built-in function
println[factorial[x]]


foo(X) :-
    \+ integer(X),
    throw(b('not even an int')).
foo(X) :-
    \+ between(1,10,X),
    throw(a('must be between 1 & 10')).
foo(X) :-
    format('~p is a valid number~n', X).

go(X) :-
    catch(
        foo(X),
        E,
        handle(E)).

handle(a(Msg)) :-
    format('~w~n', Msg),
    !.
handle(X) :- throw(X).


Procedure ErrorHandler()
  MessageRequester("Exception test", "The following error happened: " + ErrorMessage())
EndProcedure

MessageRequester("Exception test", "Test start")

OnErrorCall(@ErrorHandler())

RaiseError(#PB_OnError_InvalidMemory) ;a custom error# can also be used here depending on the OS being compiled for


import exceptions
class SillyError(exceptions.Exception):
    def __init__(self,args=None):
         self.args=args


-(long)fibonacci:(int)position
{
    long result = 0;
    if (position < 2) {
        result = position;
    } else {
        result = [self fibonacci:(position -1)] + [self fibonacci:(position -2)];
    }
    return result;
}


def factorial( n ) =
  if n < 0
    error( 'factorial: n should be non-negative' )
  else
    res = 1

    for i <- 2..n
      res *= i

    res


fun fact(n: int): int =
  if n == 0 then 1
            else n * fact(n-1)


  <flag on stack indicating if condition detected>
  if [ $ "It all went pear shaped in 'a'." message put bail ]


e <- simpleError("This is a simpleError")


#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))))


try {
    die "Help I'm dieing!";
    CATCH {
        when X::AdHoc { note .Str.uc; say "Cough, Cough, Aiee!!" }
        default { note "Unexpected exception, $_!" }
    }
}

say "Yay. I'm alive.";

die "I'm dead.";

say "Arrgh.";

CATCH {
    default { note "No you're not."; say $_.Str; }
}


let fib_iter n =
  if n < 2 then
    n
  else let fib_prev = ref 1
  and fib = ref 1 in
    for num = 2 to n - 1 do
      let temp = !fib in
        fib := !fib + !fib_prev;
        fib_prev := temp
    done;
    !fib


fun fact(n: int): int =
  loop (out = 1) = for i < n do
    out * (i+1)
  in out


window 1, @"Factorial", ( 0, 0, 300, 550 )

local fn factorialIterative( n as long ) as double
  double f
  long i

  if ( n > 1 )
    f = 1
    for i = 2 to n
      f = f * i
    next
  else
    f = 1
  end if
end fn = f

local fn factorialRecursive( n as long ) as double
  double f

  if ( n < 2 )
    f = 1
  else
    f = n * fn factorialRecursive( n -1 )
  end if
end fn = f

long i

for i = 0 to 12
  print "Iterative:"; using "####"; i; " = "; fn factorialIterative( i )
  print "Recursive:"; using "####"; i; " = "; fn factorialRecursive( i )
  print
next

HandleEvents


42 as custom_error

define foo
    custom_error throw

try
    foo
catch
    custom_error =
    if  'oops' print


/*REXX program demonstrates handling an exception (negative #); catching is via a label.*/
          do j=9  by -5
          say  'the square root of '       j       " is "       sqrt(j)
          end   /*j*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
sqrt: procedure;  parse arg x;  if x=0  then return 0;        d=digits();    h=d+6;   m.=9
      numeric digits;           numeric form;                 if x<0  then signal .sqrtNeg
      parse value format(x, 2, 1, , 0) 'E0'  with  g 'E' _ .;             g=g * .5'e'_ % 2
         do j=0  while h>9;      m.j=h;               h=h%2 + 1;          end  /*j*/
         do k=j+5  to 0  by -1;  numeric digits m.k;  g=(g+x/g) * .5;     end  /*k*/
      numeric digits d;          return  g/1
.sqrtNeg: say  'illegal SQRT argument (argument is negative):'   x;       exit 13


Try
   see 1/0
Catch
   raise("Sorry we can't divide 1/0 + nl)
Done


% recursive
function fibo = recfibo(n)
  if ( n < 2 )
    fibo = n;
  else
    fibo = recfibo(n-1) + recfibo(n-2);
  endif
endfunction


' Task: Factorial
' Language: Gambas
' Author: Sinuhe Masan (2019)
' Function factorial iterative
Function factorial_iter(num As Integer) As Long
  Dim fact As Long
  Dim i As Integer

  fact = 1
  If num > 1 Then
    For i = 2 To num
      fact = fact * i

    Next

  Endif

  Return fact

End

' Function factorial recursive
Function factorial_rec(num As Integer) As Long

  If num <= 1 Then
    Return 1

  Else
    Return num * factorial_rec(num - 1)

  Endif

End

Public Sub Main()
  Print factorial_iter(6)
  Print factorial_rec(7)

End


# define an exception
class SillyError < Exception
end


// IO error is used here just as an example of an already existing
// Error
use std::io::{Error, ErrorKind};

// Rust technically doesn't have exception, but different
// types of error handling. Here are two examples of results.

fn valid_function() -> Result<usize, Error> {
    Ok(100)
}

fn errored_function() -> Result<usize, Error> {
    Err(Error::new(ErrorKind::Other, "Something wrong happened."))
}

// This should happen only when an unrecoverable error happened
fn panicking_function() {
    panic!("Unrecoverable state reached");
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_valid_function() {
        let result = match valid_function() {
            Ok(number) => number,
            Err(_) => panic!("This is not going to happen"),
        };
        assert_eq!(result, 100);
    }

    #[test]
    fn test_errored_function() {
        let result = match errored_function() {
            Ok(_) => panic!("This is not going to happen"),
            Err(e) => {
                assert_eq!(e.to_string(), "Something wrong happened.");
                0
            }
        };
        assert_eq!(result, 0);
    }

    #[test]
    #[should_panic]
    fn test_panicking_function() {
        panicking_function();
    }
}


//Defining exceptions
class AccountBlockException extends Exception
class InsufficientFundsException(val amount: Double) extends Exception

class CheckingAccount(number: Int, var blocked: Boolean = false, var balance: Double = 0.0) {
  def deposit(amount: Double) { // Throwing an exception 1
    if (blocked) throw new AccountBlockException
    balance += amount
  }

  def withdraw(amount: Double) { // Throwing an exception 2
    if (blocked) throw new AccountBlockException
    if (amount <= balance) balance -= amount
    else throw new InsufficientFundsException(amount - balance)
  }
}

object CheckingAccount extends App {

  class ExampleException1 extends Exception

  val c = new CheckingAccount(101)
  println("Depositing $500...")
  try {
    c.deposit(500.00)
    println("\nWithdrawing $100...")
    c.withdraw(100.00)
    println("\nWithdrawing $600...")
    c.withdraw(600.00)
  } catch { // Exception handler
    case ac: InsufficientFundsException => println(s"Sorry, but you are short ${'$'} ${ac.amount}")
    case ac: AccountBlockException      => println("Account blocked.")

    ///////////////////////////// An example of multiple exception handler ////////////////////////
    case e@(_: ExampleException1 |
      _: InterruptedException) => println(s"Out of memory or something else.")

    case e: Exception => e.printStackTrace()
    case _: Throwable => // Exception cached without any action
  } finally println("Have a nice day")
}

object CheckingBlockingAccount extends App {
  val c = new CheckingAccount(102, true)
  println("Depositing $500...")
  try {
    c.deposit(500.00)
    println("\nWithdrawing $100...")
    c.withdraw(100.00)
    println("\nWithdrawing $600...")
    c.withdraw(600.00)
  } catch { // Exception handler
    case ac: InsufficientFundsException => println(s"Sorry, but you are short ${'$'} ${ac.amount}")
    case ac: AccountBlockException      => println("Account blocked.")
    case e: Exception                   => e.printStackTrace()
    case _: Throwable                   =>
  } finally println("Have a nice day")
}

object NotImplementedErrorTest extends App {
  ??? // Throws  scala.NotImplementedError: an implementation is missing
}


: fib   0 1 rot #[ tuck + ] times drop ;


# Built-in
Factorial(5);

# An implementation
fact := n -> Product([1 .. n]);


def factorial (n)
    if (< n 2) 1
      * n
        factorial (- n 1)


(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!")))


const proc: foo is func
  begin
    raise RANGE_ERROR;
  end func;


try  {
    die "I'm dead!";        # throws an exception of type 'error'
}
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!