Individual error / exception increase

I play with Pharo and want to raise a configured error / exception / something, but I have no idea how.
I looked at the relevant (I think) chapters of Faro's Leading by Example and Deep Into Faro; but couldn’t cheat on heads or tails - it seems to be above the level I need ...

I have a setter for a variable and would like to raise an error / exception if the input is not Integer:

    MyClass >> someVariable: anInteger
       anInteger isInteger
          ifFalse: [self SomehowProtestLoadly - the part I don't know how to do].
       someVariable: = anInteger

Just interrupting or exiting will be enough ... but, if possible, I would like to do it with a little more "flash" - and in a more explanatory way ...

+4
source share
1 answer

The easiest way is to simply signal a common error:

someVariable: anInteger
  anInteger isInteger
    ifFalse: [self error: 'must be an Integer'].
  someVariable := anInteger

Now, if you want to report a specific error, do the following:

  • Subclass Errorlet's sayNonIntegerArgument
  • Write your code as follows

    someVariable: anInteger
      anInteger isInteger
        ifFalse: [NonIntegerArgument signal: 'must be an Integer'].
      someVariable := anInteger
    
  • To handle this exception, do the following

    [myObject someVariable: self value]
      on: NonIntegerArgument
      do: [:ex | self handleException: ex]
    

Please note that your exception may provide additional information, such as the actual argument that was sent. To do this, add the instance variable to the class NonIntegerArgument, namely argument. Add a getter and setter for it. Then

NonIntegerArgument class >> #signal: aString argument: anObject
  ^self new
    argument: anObject;
    signal: aString

and use it that way

someVariable: anInteger
  anInteger isInteger
    ifFalse: [
      NonIntegerArgument
        signal: 'must be an Integer'
        argument: anInteger].
  someVariable := anInteger

Now the variable exwill be able to respond with an argumentoffensive message.

+4
source

Source: https://habr.com/ru/post/1688410/


All Articles