Use ruby s built in tools to handle errors and exceptions and even write your own custom exceptions.
Ruby error handling.
We call this exception handling.
In ruby exception handling is a process which describes a way to handle the error raised in a program.
Exception is the root of the exception class library the.
It s vastly easier to use than error codes.
New msg nil exception click to toggle source.
So exceptions are used to handle various type of errors which may occur during a program execution and take appropriate action instead of halting program completely.
Handling an exception to do exception handling we enclose the code that could raise an exception in a begin end block and use one or more rescue clauses to tell ruby the types of exceptions we want to handle.
You get a chance to handle recover from the error.
Here error means an unwanted or unexpected event which occurs during the execution of a program i e.
Exceptions are special types of objects in ruby that allow you to handle errors in your code.
At a minimum you can provide a graceful shutdown and reporting of problems in your code.
After reading 2 or 3 articles on the basics of ruby exception handling you re bound to see the advice on never rescuing exception.
Ruby gives you a few keywords to implement error recovery in your code.
In a nutshell every custom ruby exception should extend standarderror rather than the exception class the reason for this is outlined in exception handling in ruby.
These keywords are begin rescue.
So these types of errors were handled by the rescue block.
Otherwise create a new exception object of the same class as the receiver but with a message equal to string to str.
Construct a new exception object optionally passing in a message.
With this in mind the simplest custom exception class that we can define will look something like this.
Use ruby s built in tools to handle errors and exceptions and even write your own custom exceptions.
Class mycustomexception standarderror end.
Ruby provide a nice mechanism to handle exceptions.
Ruby exceptions and error handling is not the most remarkable feature of the ruby language.
Two ruby statements have default exception classes.
At run time that disrupts the normal flow of the program s instructions.