Exceptions

From Rosetta Code
Revision as of 05:46, 12 November 2007 by rosettacode>Mwn3d (Re-alphabetized.)
Task
Exceptions
You are encouraged to solve this task according to the task description, using any language you may know.
Control Structures

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++

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.

try-catch

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

 void foo()
 {
   throw MyException();
 }

 void call_foo()
 {
   try {
     foo();
   }
   catch (MyException &exc)
   {
     // handle exceptions of type MyException and derived
   }
   catch (...)
   {
     // handle any type of exception not handled by above catches
   }
 }

C#

Compiler: MSVS 2005

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

 void foo()
 {
   throw MyException();
 }

 void call_foo()
 {
   try {
     foo();
   }
   catch (MyException e)
   {
     // handle exceptions of type MyException and derived
   }
   catch
   {
     // handle any type of exception not handled by above catches
   }
 } 

Forth

Forth's exception mechanism is, like most things in Forth, very simple but powerful. CATCH captures the data and return stack pointers, then exectutes 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


Java

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


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

Interpreter: PHP 5.0+

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

try-except-finally-else

Interpreter: Python 2.5

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

try:
   foo()
except TypeError:
   bar()
finally:
   baz()
else:
   # no exception occurred
   quux()

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;