Exceptions: Difference between revisions

Content deleted Content added
mNo edit summary
No edit summary
Line 4: Line 4:
=={{header|Ada}}==
=={{header|Ada}}==
===Define an exception===
===Define an exception===
<ada>
<lang ada>
Foo_Error : exception;
Foo_Error : exception;
</ada>
</lang>
===Raise an exception===
===Raise an exception===
<ada>
<lang ada>
procedure Foo is
procedure Foo is
begin
begin
raise Foo_Error;
raise Foo_Error;
end Foo;
end Foo;
</ada>
</lang>
Re-raising once caught exception:
Re-raising once caught exception:
<ada>
<lang ada>
...
...
exception
exception
Line 22: Line 22:
raise; -- continue propagation of
raise; -- continue propagation of
end if;
end if;
</ada>
</lang>
===Handle an exception===
===Handle an exception===
<ada>
<lang ada>
procedure Call_Foo is
procedure Call_Foo is
begin
begin
Line 34: Line 34:
... -- this catches all other exceptions
... -- this catches all other exceptions
end Call_Foo;
end Call_Foo;
</ada>
</lang>
===Ada.Exceptions===
===Ada.Exceptions===
The standard package Ada.Exceptions provides a possibility to attach messages to exceptions, to get exception occurrence information and textual description of exceptions. The following example illustrates basic functionality of:
The standard package Ada.Exceptions provides a possibility to attach messages to exceptions, to get exception occurrence information and textual description of exceptions. The following example illustrates basic functionality of:
<ada>
<lang ada>
with Ada.Exceptions; use Ada.Exceptions;
with Ada.Exceptions; use Ada.Exceptions;
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Text_IO; use Ada.Text_IO;
Line 50: Line 50:
Put_Line ("Something is wrong here" & Exception_Information (Error));
Put_Line ("Something is wrong here" & Exception_Information (Error));
end Main;
end Main;
</ada>
</lang>
=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
===Define an exception===
===Define an exception===
Line 177: Line 177:


===Defining exceptions===
===Defining exceptions===
<cpp>
<lang cpp>
struct MyException
struct MyException
{
{
// data with info about exception
// data with info about exception
};
};
</cpp>
</lang>


There's also a class <code>std::exception</code> which you can, but are not required to derive your exception class from. The advantage of doing so is that you can catch unknown exceptions and still get some meaningful information out. There are also more specific classes like <code>std::runtime_error</code> which derive from <code>std::exception</code>.
There's also a class <tt>std::exception</tt> which you can, but are not required to derive your exception class from. The advantage of doing so is that you can catch unknown exceptions and still get some meaningful information out. There are also more specific classes like <tt>std::runtime_error</tt> which derive from <tt>std::exception</tt>.


<cpp>
<lang cpp>
#include <exception>
#include <exception>
struct MyException: std::exception
struct MyException: std::exception
Line 192: Line 192:
char const* what() const throw() { return "description"; }
char const* what() const throw() { return "description"; }
}
}
</cpp>
</lang>


Note that in principle you can throw any copyable type as exception, including built-in types.
Note that in principle you can throw any copyable type as exception, including built-in types.


===Throw exceptions===
===Throw exceptions===
<cpp>
<lang cpp>
// this function can throw any type of exception
// this function can throw any type of exception
void foo()
void foo()
Line 215: Line 215:
throw MyException();
throw MyException();
}
}
</cpp>
</lang>


===Catching exceptions===
===Catching exceptions===
<cpp>
<lang cpp>
try {
try {
foo();
foo();
Line 236: Line 236:
// handle any type of exception not handled by above catches
// handle any type of exception not handled by above catches
}
}
</cpp>
</lang>


=={{header|C sharp|C #}}==
=={{header|C sharp|C #}}==
Line 327: Line 327:


=={{header|Haskell}}==
=={{header|Haskell}}==
Exceptions can be implemented using monads; no special syntax is necessary.[http://haskell.org/haskellwiki/Exception] In GHC, specialized functionality for exceptions are provided by the <code>Control.Exception</code> module.
Exceptions can be implemented using monads; no special syntax is necessary.[http://haskell.org/haskellwiki/Exception] In GHC, specialized functionality for exceptions are provided by the <tt>Control.Exception</tt> module.


===Defining exceptions===
===Defining exceptions===
Line 362: Line 362:


=={{header|J}}==
=={{header|J}}==
Program<code> u :: v </code>executes <code>u</code> and provides its result as output unless an error occurs. In case of error, the result of <code>v</code> is provided instead.<br>
Program<tt> u :: v </tt>executes <tt>u</tt> and provides its result as output unless an error occurs. In case of error, the result of <tt>v</tt> is provided instead.<br>


An exception in an explicit definition can be detected with <code>try.</code> and <code>catcht.</code> and can be thrown with <code> throw. </code> as seen below.
An exception in an explicit definition can be detected with <tt>try.</tt> and <tt>catcht.</tt> and can be thrown with <tt> throw. </tt> as seen below.


pickyPicky =: verb define
pickyPicky =: verb define
Line 610: Line 610:
===Defining an exception===
===Defining an exception===


<python> import exceptions
<lang python> import exceptions
class SillyError(exceptions.Exception):
class SillyError(exceptions.Exception):
def __init__(self,args=None):
def __init__(self,args=None):
self.args=args</python>
self.args=args</lang>


Note: In most cases new exceptions are defined simply using the ''pass'' statement. For example:
Note: In most cases new exceptions are defined simply using the ''pass'' statement. For example:


<python>
<lang python>
class MyInvalidArgument(ValueError):
class MyInvalidArgument(ValueError):
pass
pass
</python>
</lang>


This example makes "MyInvalidArgument" an type of ValueError (one of the built-in exceptions). It's simply declared as a subclass of the existing exception and no over-riding is necessary. (An except clause for ValueError would catch MyInvalidArgument exceptions ... but one's code could insert a more specific exception handler for the more specific type of exception).
This example makes "MyInvalidArgument" an type of ValueError (one of the built-in exceptions). It's simply declared as a subclass of the existing exception and no over-riding is necessary. (An except clause for ValueError would catch MyInvalidArgument exceptions ... but one's code could insert a more specific exception handler for the more specific type of exception).
Line 626: Line 626:
===Throwing an exception===
===Throwing an exception===


<python>def spam():
<lang python>def spam():
raise SillyError, 'egg'</python>
raise SillyError, 'egg'</lang>


===Handling an exception===
===Handling an exception===
Line 634: Line 634:
try-except-finally-else
try-except-finally-else


<python> try:
<lang python> try:
foo()
foo()
except SillyError, se:
except SillyError, se:
Line 643: Line 643:
else:
else:
# no exception occurred
# no exception occurred
quux()</python>
quux()</lang>


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).
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).
Line 666: Line 666:
===Defining an exception===
===Defining an exception===


<ruby>class SillyError < Exception
<lang ruby>class SillyError < Exception
def initialize(args = nil)
def initialize(args = nil)
@args = args
@args = args
end
end
end</ruby>
end</lang>


Note: Often new exceptions are defined simply with no body. For example:
Note: Often new exceptions are defined simply with no body. For example:


<ruby>class MyInvalidArgument < ArgumentError
<lang ruby>class MyInvalidArgument < ArgumentError
end</ruby>
end</lang>


This example makes "MyInvalidArgument" an type of ArgumentError (one of the built-in exceptions). It's simply declared as a subclass of the existing exception and no over-riding is necessary. (A rescue clause for ArgumentError would catch MyInvalidArgument exceptions ... but one's code could insert a more specific exception handler for the more specific type of exception).
This example makes "MyInvalidArgument" an type of ArgumentError (one of the built-in exceptions). It's simply declared as a subclass of the existing exception and no over-riding is necessary. (A rescue clause for ArgumentError would catch MyInvalidArgument exceptions ... but one's code could insert a more specific exception handler for the more specific type of exception).
Line 681: Line 681:
===Throwing an exception===
===Throwing an exception===


<ruby>def spam
<lang ruby>def spam
raise SillyError, 'egg'
raise SillyError, 'egg'
end</ruby>
end</lang>


===Handling an exception===
===Handling an exception===
Line 689: Line 689:
rescue/else/ensure
rescue/else/ensure


<ruby>begin
<lang ruby>begin
foo
foo
rescue SillyError, se
rescue SillyError, se
Line 699: Line 699:
ensure
ensure
baz
baz
end</ruby>
end</lang>


The "rescue" clause is like the "catch" clause in other languages. The "ensure" clause is like the "finally" clause in other languages.
The "rescue" clause is like the "catch" clause in other languages. The "ensure" clause is like the "finally" clause in other languages.
Line 706: Line 706:
Ruby has a separate exception-like system that is meant to be used to exit out of deep executions that are not errors.
Ruby has a separate exception-like system that is meant to be used to exit out of deep executions that are not errors.


<python>def foo
<lang python>def foo
throw :done
throw :done
end
end
Line 712: Line 712:
catch :done do
catch :done do
foo
foo
end</python>
end</lang>


You can only "throw" and "catch" symbols. Like exceptions, the throw can be made from a function defined elsewhere from the catch block.
You can only "throw" and "catch" symbols. Like exceptions, the throw can be made from a function defined elsewhere from the catch block.