Exceptions: Difference between revisions

From Rosetta Code
Content added Content deleted
No edit summary
(Added AppleScript version)
Line 1: Line 1:
{{task}}
{{task}}

This task is to give an example of an exception handling routine.

==[[AppleScript]]==
[[Category:AppleScript]]
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


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

Revision as of 23:36, 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.

AppleScript

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

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