Exceptions: Difference between revisions
Content added Content deleted
(Visual basic) |
(started ruby) |
||
Line 626: | Line 626: | ||
custom_error = |
custom_error = |
||
if 'oops' print |
if 'oops' print |
||
=={{header|Ruby}}== |
|||
===Defining an exception=== |
|||
<ruby>class SillyError < Exception |
|||
def initialize(args = nil) |
|||
@args = args |
|||
end |
|||
end</ruby> |
|||
Note: Often new exceptions are defined simply with no body. For example: |
|||
<ruby>class MyInvalidArgument < ArgumentError |
|||
end</ruby> |
|||
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). |
|||
===Throwing an exception=== |
|||
<ruby>def spam |
|||
raise SillyError, 'egg' |
|||
end</ruby> |
|||
===Handling an exception=== |
|||
rescue/else/ensure |
|||
<ruby>begin |
|||
foo |
|||
rescue SillyError, se |
|||
print se.args |
|||
bar() |
|||
else |
|||
# no exception occurred |
|||
quux |
|||
ensure |
|||
baz |
|||
end</ruby> |
|||
The "rescue" clause is like the "catch" clause in other languages. The "ensure" clause is like the "finally" clause in other languages. |
|||
===Catch/Throw=== |
|||
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 |
|||
throw :done |
|||
end |
|||
catch :done do |
|||
foo |
|||
end</python> |
|||
You can only "throw" and "catch" symbols. Like exceptions, the throw can be made from a function defined elsewhere from the catch block. |
|||
=={{header|Standard ML}}== |
=={{header|Standard ML}}== |