Exceptions: Difference between revisions

From Rosetta Code
Content added Content deleted
No edit summary
Line 1:
{{task}}
==[[Python]]==
[[Category: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()
 
==[[C plus plus|C++]]==
[[Category:C plus plus]]
 
C++ has no finally construct. Instead you can do this in the
Line 50 ⟶ 34:
}
}
 
==[[Python]]==
[[Category: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()

Revision as of 21:48, 25 January 2007

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

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