Next: , Up: Exception handling  


6.11.1 Creating exceptions

GNU Smalltalk provides a few exceptions, all of which are subclasses of Exception. Most of the ones you might want to create yourself are in the SystemExceptions namespace. You can browse the builtin exceptions in the base library reference, and look at their names with Exception printHierarchy.

Some useful examples from the system exceptions are SystemExceptions.InvalidValue, whose meaning should be obvious, and SystemExceptions.WrongMessageSent, which we will demonstrate below.

Let’s say that you change one of your classes to no longer support #new for creating new instances. However, because you use the first-class classes feature of Smalltalk, it is not so easy to find and change all sends. Now, you can do something like this:

Object subclass: Toaster [
    Toaster class >> new [
        ^SystemExceptions.WrongMessageSent
            signalOn: #new useInstead: #toast:
    ]

    Toaster class >> toast: reason [
        ^super new reason: reason; yourself
    ]

    ...
]

Admittedly, this doesn’t quite fit the conditions for using exceptions. However, since the exception type is already provided, it is probably easier to use it than #error: when you are doing defensive programming of this sort.