Open In App
Related Articles

Ruby | Exceptions

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report
A good program(or programmer) predict error and arrange to handle them in an effective manner. This is not as easy as it sounds. Exceptions are the errors that occur at runtime. It halts the execution of a program. They are caused by an extensive variety of exceptional circumstances, such as running out of memory, not being able to open a file, trying to initialize an object to an impossible value etc.
What is an Exception?
An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at runtime, that disrupts the normal flow of the program’s instructions.
Error vs Exception
Errors:
  • Errors are unexpected issues that may arise during computer program execution.
  • Errors cannot be handled.
  • All Errors are exceptions.
Exceptions:
  • Exceptions are unexpected events that may arise during run-time.
  • Exceptions can be handled using try-catch mechanisms.
  • All exceptions are not errors.
Traditional Approach to Handle Exceptions
The traditional approach to handle the exception includes the use of return codes. The open method returns some specific value and says it failed. This value is then transmitted back to the layer of calling routines until someone wants to take responsibility for it. The problem with this approach is that managing all these errors was very complex. If a method calls open, the read and at last it calls close then there is a possibility in which each can return an error indication. Now, how the function will differentiate between these error codes in the value that it returns to its caller. Here exception class provides a solution for this problem. Exception class provides a package information to the program or programmer about an error into an object. The exception object sends back to the calling stack until the system finds the suitable code that knows how to handle the occurred error.
Exception Class & Its Hierarchy
It is the package that contains the information about the exception in an object. Ruby contains a predefined hierarchy of exceptions as shown below: In the above diagram, most of the exceptions come under StandardError class, which are the general exceptions arises in the Ruby program. The remaining exceptions describe more serious, lower-level, and less recoverable situations, that Ruby programs do not don’t try to handle them. When a user wants to create an exception, he can use one of the built-in exception class. In Ruby, a user can also create his own exception but for that, he has to make that exception a subclass of StandardError or one of its child class. If he didn’t define in StandardError then the exception would not be caught by default. Every exception contains message string and a stack backtrack. So, if the user defines his own exception then he has to add this information in it.
Example:

                    
Runtime Error:
source_file.rb:10:in `/’: divided by 0 (ZeroDivisionError) from source_file.rb:10:in `
Explanation: In the above program, the user is trying to divide 14 by 0. So here Ruby compiler will throw an exception as ZeroDivisionError.
Creating User-Defined Exception: Ruby uses the kernel method termed as raise to create the exceptions which will be the instance of Exception class or one of its subclass. rescue clause is used to handle the exceptions created by raise. Example:
# Ruby program to create the user defined exception
  
# defining a method
def raise_exception
      
    puts 'This is Before Exception Arise!'     
      
    # using raise to create exception  
    raise 'Exception Created'     
      
    puts 'This is After Exception Arise -- Not Displayed'     
end     
  
# Calling the method
raise_exception

                    
Output:
This is Before Exception Arise!
source_file.rb:9:in `raise_exception': Exception Created (RuntimeError)
    from source_file.rb:15:in `
'
Solution of above Example Code:
# Ruby program to create the user 
# defined exception and rescued 
  
# defining a method
def raise_and_rescue     
  begin 
        
    puts 'This is Before Exception Arise!'
        
    # using raise to create an exception  
    raise 'Exception Created!'
  
    puts 'After Exception'  
  
  # using Rescue method
  rescue     
    puts 'Finally Saved!'     
    
end     
  
puts 'Outside from Begin Block!'     
  
end     
  
# calling method
raise_and_rescue    

                    
Output:
This is Before Exception Arise!
Finally Saved!
Outside from Begin Block!
Explanation: In the above example the exception is raised by the raise method(The raise method directly comes from the kernel module) and the code is interrupted due to the presence of an exception. Now, this exception is handled by the rescue clause and the flow of program continue without error after rescue clause. If a program contains more than one rescue clause then if first rescue code is unable to handle the exception then the next rescue clause will handle the exception.

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!


Last Updated : 18 Sep, 2018
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads