-
Represents some kind of exceptional or error condition
It indicates that something has gone wrong.
-
Exceptions are raised.
-
An exception is a special kind of object, an instance of the class Exception. Or it may be a descendant of that class.
-
Ruby has some predefined classes - Exception and its children.
-
By default, Ruby programs terminate when an exception occurs.
-
It is possible to declare exception handlers.
An exception handler is a block of code that is executed if an exception occurs during the execution of some other block of code.
-
Raising an exception means:
- Stopping normal execution of the program.
- Tansferring the flow-of-control to the exception handling code.
- Divide a number by Zero. See demo
- Open a file that doesn't exist.
- User enters the wrong type of input. See demo
- A method determines that an argument passed to is not correct. See demo
- Calling a method on an object that it does have. See demo
- Typing Control-C on the terminal while a Ruby program is Running. See demo
- RubyOnRails has many methods that can raise and exception. See demo
- Invalid input from a form.
- Saving an object to the Database that is not valid.
Look at div_by_zero.rb. Notice how it raises a "Divide by Zero" exception.
Run it.
ruby div_by_zero.rb
Rescue the exception and show the exception attributes.
ruby div_by_zero_exception.rb
Do the above for argument_error.rb and argument_error_retry
Create a ruby app to guess a number. Give the user 3 tries. Use retry
Look at Person class with a PersonValid exception class.
Use this PersonValid exception class to validate people.
- Create a Person class with a name and an age.
- Add a Person instance method to check if the name is has from 2 to 9 characters.
- Add a Person instance method to check if the person has a valid age. Greater than 0 and less than 110.
[ {john: 44}, {mary:, 33}, {bill: 22}, {harry: 44, 'male'}, {sue: 26} ]
- Given this above list of hash literals, create people by passing each hash to the Person.new method.
- Ignore bad data, (hint: use rescue). Another words, don't let bad data break your program.