TopTest ProgramExceptions

Exceptions

What happens when things go wrong when we are executing a program? If we can anticipate a problem then we should write code to test for the problem. But sometimes problems occur because of unforeseen actions by a user or some other problem that the programmer has no control over (e.g., a file disappearing).

You've seen plenty of run-time errors resulting from problems in your code. Today we learn how to catch these before they crash the program. The general construct is

  try {
     stuff to try
  catch{ ex: SomeExceptionType ->
      // stuff to do if exception occurs
  }

Here is a first simple example. Remember our color match program. Suppose someone puts in an illegal color value. What do we want to happen. Right now if that happens, the program will simply crash. But look at the definition of the color class in objectdraw:

// Simple color class
class color.r(r' : Number) g(g' : Number) b(b' : Number) -> Color {
  if((r' < 0) || (r' > 255)) then {
    ColorOutOfRange.raise "red index {r'} out of bounds 0..255"
  }

  if((g' < 0) || (g' > 255)) then {
    ColorOutOfRange.raise "green index {g'} out of bounds 0..255"
  }

  if((b' < 0) || (b' > 255)) then {
    ColorOutOfRange.raise "blue index {b'} out of bounds 0..255"
  }

  def red:Number is public = r'
  def green:Number is public = g'
  def blue:Number is public = b'

  method asString -> String {
    "rgb({red}, {green}, {blue})"
  }
}

Note the statements of the form ColorOutOfRange.raise "red index r' out of bounds 0..255" ColorOutOfRange is an exception, declared as:

def ColorOutOfRange : ExceptionKind is public =
  RuntimeError.refine "Color Out Of Range"

We can now "catch that exception when our code puts in an illegal value.


  method changeColor -> Done {
    var newColor: Color
    try {
      newColor := color.r(redField.number)
                                  g(greenField.number)
                                  b(blueField.number)
    } catch {
      ex:ColorOutOfRange ->
        print "Enter values between 0 and 255 for colors"
        newColor := black
    }
    background.color := newColor
  }

The parameter ex can also provide extra information. Here are some of its methods:

Here is an example with a different kind of exception:

def myList:List<Number> = list.with(5,7,9)
var index:= 1
try {
  while {index < 7} do {
    print(myList.at(index))
    index := index + 1
  }
} catch {ex:BoundsError ->
  print "went too far!"
  print ("on line {ex.lineNumber} of {ex.moduleName}, {ex.message}")
  // print "\n\nBacktrace: {ex.backtrace}"
}

In this method, the loop terminates when index goes up to four. It then prints out information about what happened.


TopTest ProgramExceptions