Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 5.3

...

An exception stops the program if it is not caught.

Code Block
borderStylesolid
titleDivision by Zero
borderStylesolid
print 1 / 0
No Format
bgColor#D8DDE9
titleOutput
borderStylesolid
titleOutput
System.DivideByZeroException: Attempted to divide by zero.
   at Test.Main(String[] argv)

...

To handle the situation, exceptions must be caught.
Exceptions are either caught in a try-except statement, a try-ensure statement, or a try-except-ensure statement.
Also, all Exceptions are derived from the simple Exception.

Code Block
borderStylesolid
titletry-except example
borderStylesolid
import System

try:
    print 1 / 0
except e as DivideByZeroException:
    print "Whoops"
print "Doing more..."
No Format
bgColor#D8DDE9
titleOutput
borderStylesolid
titleOutput
Whoops
Doing more...

This prevents the code from stopping and lets the program keep running even after it would have normally crashed.

...

Try-ensure is handy if you are dealing with open streams that need to be closed in case of an error.

Code Block
borderStylesolid
titletry-ensure example
borderStylesolid
import System

try:
    s = MyClass()
    s.SomethingBad()
ensure:
    print "This code will be executed, whether there is an error or not."
No Format
bgColor#D8DDE9
titleOutput
borderStylesolid
titleOutput
This code will be executed, whether there is an error or not.
System.Exception: Something bad happened.
   at Test.Main(String[] argv)

...

A try-except-ensure combines the two.

Code Block
borderStylesolid
titletry-except-ensure example
borderStylesolid
import System

try:
    s = MyClass()
    s.SomethingBad()
except e as Exception:
    print "Problem! $(e.Message)"
ensure:
    print "This code will be executed, whether there is an error or not."
No Format
bgColor#D8DDE9
titleOutput
borderStylesolid
titleOutput
Problem: Something bad happened.
This code will be executed, whether there is an error or not.

...

There are times that you want to raise Exceptions of your own.

Code Block
borderStylesolid
titleRaising an Exception
borderStylesolid
import System

def Execute(i as int):
    if i < 10:
        raise Exception("Argument i must be greater than or equal to 10")
    print i

...