Exceptions
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
You are encouraged to solve this task according to the task description, using any language you may know.
These are examples of control structures. You may also be interested in:
This task is to give an example of an exception handling routine and to "throw" a new exception.
Ada
Define an exception
Foo_Error : Exception;
Raise an exception
procedure Foo is begin raise Foo_Error; end Foo;
Handle an exception
procedure Call_Foo is begin Foo; exception when Foo_Error => -- do something end Call_Foo;
AppleScript
try
try set num to 1 / 0 --do something that might throw an error end try
try-on error
try set num to 1 / 0 --do something that might throw an error on error errMess number errNum --errMess and number errNum are optional display alert "Error # " & errNum & return & errMess end try
error
error "Error message." number 2000
C
The setjmp()/longjmp() functions in the C standard library header <setjmp.h> are typically used for exception handling.
try-catch
#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 */ } }
C++
C++ has no finally construct. Instead you can do this in the destructor of an object on the stack, which will be called if an exception is thrown.
The exception can be of any type, this includes int's, other primitives, as well as objects.
Defining exceptions
struct MyException { // data with info about exception };
Throw exceptions
// this function can throw any type of exception void foo() { throw MyException(); }
// this function can only throw the types of exceptions that are listed void foo2() throw(MyException) { throw MyException(); }
Catching exceptions
try { foo(); } catch (MyException &exc) { // handle exceptions of type MyException and derived } catch (...) { // handle any type of exception not handled by above catches }
C#
Defining exceptions
public class MyException : Exception { // data with info about exception };
Throw exceptions
void foo() { throw MyException(); }
Catching exceptions
try { foo(); } catch (MyException e) { // handle exceptions of type MyException and derived } catch { // handle any type of exception not handled by above catches }
ColdFusion
Catch Exceptions
inside <cfscript>:
try { foo(); } catch (Any e) { // handle exception e }
otherwise:
<cftry> <cfcatch type="Database|..."> </cfcatch> </cftry>
Factor
Throw Exceptions
"Install Linux, Problem Solved" throw
TUPLE: velociraptor ; \ velociraptor construct-empty throw
Catch Exceptions
! Preferred exception handling : try-foo [ foo ] [ foo-failed ] recover ;
: try-bar [ bar ] [ bar-errored ] [ bar-always ] cleanup ;
! Used rarely [ "Fail" throw ] try ! throws a "Fail" [ "Fail" throw ] catch ! returns "Fail" [ "Hi" print ] catch ! returns f (looks the same as throwing f; don't throw f) [ f throw ] catch ! returns f, bad! use recover or cleanup instead
Forth
Forth's exception mechanism is, like most things in Forth, very simple but powerful. CATCH captures the data and return stack pointers, then executes an execution token. THROW conditionally throws a value up to the most recent CATCH, restoring the stack pointers.
Throw Exceptions
: f ( -- ) 1 throw ." f " ; \ will throw a "1" : g ( -- ) 0 throw ." g " ; \ does not throw
Catch Exceptions
: report ( n -- ) ?dup if ." caught " . else ." no throw" then ; : test ( -- ) ['] f catch report ['] g catch report ;
test example. (Output shown in bold)
cr test caught 1 g no throw ok
Note that CATCH only restores the stack pointers, not the stack values, so any values that were changed during the execution of the token will have undefined values. In practice, this means writing code to clean up the stack, like this:
10 ['] myfun catch if drop then
J
Program u :: v
executes u
and provides its result as output unless an error occurs. In case of error, the result of v
is provided instead.
An exception in an explicit definition can be detected with try.
and catcht.
and can be thrown with throw.
as seen below.
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!
Java
An exception needs to extend the Exception type.
Defining exceptions
//Checked exception public class MyException extends Exception { //Put specific info in here }
//Unchecked exception public class MyRuntimeException extends RuntimeException {}
Throw exceptions
public void fooChecked() throws MyException { throw new MyException(); }
public void fooUnchecked() { throw new MyRuntimeException(); }
Catching exceptions
try { fooChecked(); } catch(MyException exc) { //Catch only your specified type of exception } catch(Exception exc) { //Catch any non-system error exception } catch(Throwable exc) { //Catch everything including system errors (not recommended) } finally { //This code is always executed after exiting the try block }
JavaScript
Throwing exceptions
function doStuff() { throw new Error('Not implemented!'); }
Catching exceptions
try { element.attachEvent('onclick', doStuff); } catch(e if e instanceof TypeError) { element.addEventListener('click', doStuff, false); } finally { eventSetup = true; }
OCaml
Defining exceptions
Like constructors, exceptions may or may not have an argument:
exception My_Exception;; exception Another_Exception of string;;
Throw exceptions
Throw exceptions with the "raise" function; the expression will match any type:
let foo x = match x with 1 -> raise My_Exception | 2 -> raise (Another_Exception "hi mom") | _ -> 5 ;;
Catching exceptions
The "with" syntax pattern-matches on the exception type and argument:
try string_of_int (foo 2) with My_Exception -> "got my exception" | Another_Exception s -> s | _ -> "unknown exception"
Perl
# throw an exception die "Danger, danger, Will Robinson!"; # catch an exception and show it eval { die "this could go wrong mightily"; }; print $@ if $@; # rethrow die $@;
See http://perldoc.perl.org/perlvar.html#%24EVAL_ERROR for the meaning of the special variable $@. See http://search.cpan.org/dist/Error for an advanced, object based exception handling.
PHP
Exceptions were not available prior to PHP 5.0
Define exceptions
class MyException extends Exception { // Custom exception attributes & methods }
Throwing exceptions
function throwsException() { throw new Exception('Exception message'); }
Catching Exceptions
try { throwsException(); } catch (Exception $e) { echo 'Caught exception: ' . $e->getMessage(); }
Pop11
Throwing exceptions
define throw_exception(); throw([my_exception my_data]); enddefine;
Catching exceptions
define main(); vars cargo; define catcher(); ;;; print exception data cargo => enddefine; catch(throw_exception, catcher, [my_exception ?cargo]); enddefine; main();
Python
Defining an exception type
import exceptions class SillyError(exceptions.Exception): def __init__(self,args=None): self.args=args
Throwing an exception
def spam(): raise SillyError, 'egg'
Handling exceptions
try-except-finally-else
try: foo() except SillyError, se: print se.args bar() finally: baz() else: # no exception occurred quux()
Before Python 2.5 it was not possible to use finally and except together. (It was necessary to nest a separate try...except block inside of your try...finally block).
Raven
42 as custom_error define foo custom_error throw try foo catch custom_error = if 'oops' print
Standard ML
Define Exceptions
exception MyException; exception MyDataException of int; (* can be any first-class type, not just int *)
Throw Exceptions
fun f() = raise MyException; fun g() = raise MyDataException 22;
Catch Exceptions
val x = f() handle MyException => 22; val y = f() handle MyDataException x => x;
V
throwing exceptions
[myproc ['new error' 1 2 3] throw 'should not come here' puts ].
catching them
[myproc] [puts] catch =[new error 1 2 3]