|
Things don't always work as expected, so far we have treated our code samples as if everything would work correctly, but in the real world, virtually all programs will generate errors at some point during use.
A file won't be in the correct format, you'll encounter errors when writing to a file, you'll run out of available memory and so on.
A good programmer will always anticipate such cases and code their program in such a way that it will be able to handle these situations gracefully.
Instead of a cryptic "erorr blaaba 0x2526wd "" message an error more like this "error when opening file" could be printed on screen.
Or, the program could congratulate you instead "Congrats, no errors encountered".
A concept named "exceptions" exists for all these cases and it's the most elegant solution to problems of this type.An exception, if you like, is the particular way a programming language is instructed to handle a certain type of error.
First of all, all Ruby exceptions are objects of the class Exceptions and its descendants.You will see later why it's important to know this.You should also know that every exception has a message 'meaning' associated with it. When you choose to define your own exceptions, you can add additional info to what's already available.
How do you tell Ruby that when certain conditions are met/not met, it needs to raise an exception and treat it?
By using the raise method.
raise
raise string
raise thing [ , string [ stack trace ] ]
raise
raise "bad file format"
raise GUIException, "GUI failure", caller
The first form reraises the exception in $!.If $! is nil, it raises a new RuntimeError exception.
The second form creates will create a new RuntimeError exception having as message the given string.
The third form creates an exception invoking the method exception as first argument. The exception’s message and backtrace are the second and third arguments.
Here's another sample:
raise "Unknown file format" if extension.nil?
What the code above does, is test if a certain file has an extension associated with it and if not, it will raise an exception with the message "Unknown file format".
Ruby exception hierarchy
|