Exceptions: Difference between revisions

From Rosetta Code
Content added Content deleted
(extended task to include trowing an exception)
Line 1: Line 1:
{{task}}
{{task}}


This task is to give an example of an exception handling routine.
This task is to give an example of an exception handling routine and to "throw" a new exception.


==[[AppleScript]]==
==[[AppleScript]]==
[[Category:AppleScript]]
[[Category:AppleScript]]
===try===
try
try
set num to 1 / 0
set num to 1 / 0
Line 10: Line 11:
end try
end try


===try-on error===
try
try
set num to 1 / 0
set num to 1 / 0
Line 17: Line 19:
display alert "Error # " & errNum & return & errMess
display alert "Error # " & errNum & return & errMess
end try
end try

===throw===
error "Error message." number 2000


==[[C plus plus|C++]]==
==[[C plus plus|C++]]==

Revision as of 23:57, 25 January 2007

Task
Exceptions
You are encouraged to solve this task according to the task description, using any language you may know.

This task is to give an example of an exception handling routine and to "throw" a new exception.

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

throw

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

Python

try-except-finally-else

Interpreter: Python 2.5

Before Python 2.5 it was not possible to use finally and except together.

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