Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
All mistakes and exceptions in Ruby are subclasses of the Exception class. Although this may seem obvious, Ruby's exception handling is a little more complex than you might anticipate because of the hierarchy of exceptions the language was created with.
Exception Handling
An exception symbolizes a rare or unusual circumstance; it denotes something has gone wrong. Attempting to divide by zero, invoking a method on an object that does not define the method, or giving a wrong parameter to a method are all examples of programming errors. It could also result from an external condition, such as trying to create an object when the system is out of memory or making a network request when the network is unavailable. An exception is thrown when one of these mistakes or situations occurs (or thrown). When a Ruby program encounters an exception, it will automatically terminate. Exception handlers, on the other hand, can be declared.
An exception handler is a block of code that is run if an exception occurs while another block of code is executed. Exceptions are a type of control statement in this sense. When an exception is raised, the flow-of-control is transferred to the exception handling code. This is similar to exiting a loop with the break statement. Exceptions, on the other hand, differ from the break statement in that they can transfer control out of many enclosing blocks and even up the call stack to reach the exception handler.
Ruby raises exceptions with the Kernel method and handles them with a rescue clause. The Exception class, or one of its numerous subclasses, is used to raise exceptions. The following article uses the rescue clause as a statement modifier in great depth.
Handling Exceptions with Rescue
The Ruby language has a rescue clause as standard. Rescue is a clause that can be added to other Ruby statements rather than a statement in and of itself. A rescue clause frequently accompanies a begin statement. The begin statement's sole purpose is to delimit the code block in which exceptions will be handled. The following is an example of a begin statement with a rescue clause:
begin
# Any number of Ruby statements go here.
# Usually, they are executed without exceptions and
# execution continues after the end statement.
rescue
# This is the rescue clause; the exception-handling code goes here.
# If an exception is raised by the code above or propagates up
# from one of the methods called above, then execution jumps here.
end
Rescue With Methods
Just like a begin statement, a def statement that defines a method may also contain exception-handling code in rescue, otherwise, and assure clauses. These exception handling clauses are placed after the method body's conclusion but before the def statement's conclusion. Associating your rescue clauses with the def statement can be organized in short methods. As a result, you can avoid using begin statements and the additional level of indentation they require.
Exception Objects
All details of "what happened" during an exception are stored in exception objects. When rescuing, we are aware of how to extract the exception object. Consequently, exception objects are examples of exception classes. That much is obvious. We construct a new exception object and raise it in the following example. If we catch it, we'll be able to confirm that it's the same thing we raised.
Example:
my_exception = RuntimeError.new
begin
raise my_exception
rescue => e
puts(e == my_exception) # prints "true"
end
Not all classes are appropriate for exception use. It can only be used by those who inherit from Exception. Exception sits immediately at the top of our diagram of the hierarchy of exception classes.
Class
The class name of an exception object is the first, and maybe most crucial, piece of information about it. Classes like ActiveRecord and ZeroDivisionError:: Exactly what went wrong is shown by RecordNotFound. It may be advantageous to create your exception classes to specify exceptional conditions because your code is unique. Build a class that derives from another type of Exception to do this. To inherit from StandardError is the most popular strategy. It's a good idea to adhere to this strategy if your exception is a specific type of fault.
You've seen how saving StandardError also saves all of its child classes' exceptions and those of that class. Utilizing this behavior, you can design your exception groups that are simple to recover from.
Example:
class NetworkError < StandardError
end
class TimeoutError < NetworkError
end
class UnreachableError < NetworkError
end
begin
network_stuff
rescue NetworkError => e
# this also rescues TimeoutError and UnreachableError
# because they inherit from NetworkError
end
BackTree
Backtree is what shows you what line of code malfunctioned when your software crashed. The exception object contains the backtrace data. It is produced by the raise method using Kernel#caller, and it is then saved in the exception using Exception#set backtrace. Simply put, the trace is an array of strings. We can look at it as follows:
begin
raise "FOO"
rescue => e
e.backtrace[0..3].each do |line|
puts line
end
end
If you ever need to "convert" one exception into another, you can also set the backtrace. You might also wish to set a backtrace that points to a line in the template rather than a line of Ruby code if you're developing a template engine:
The raised Ruby exception is tested against each parameter for each rescue clause, and the match is successful if the exception in the clause is the same as or a superclass of the exception that was thrown. The else block is invoked if the thrown Ruby exception does not fit one of the listed exception categories.
How does Ruby rescue work?
When an exception reaches the top of the call stack, it can be saved to keep your program from crashing. The rescue keyword in Ruby is used for this. In Ruby, you can designate a particular error class from which to recover an exception.
How does Ruby catch errors?
Using the rescue block, you can catch an exception before starting the begin block over using the retry statement.
What does Rails' rescue function do?
By giving you an easy approach to handling frequent problems that might occur in your software, Rescue enables you to develop more durable solutions. At the very least, you can offer a graceful shutdown and bug reporting for your code. Check out Retrace for Ruby if you're searching for something more robust.
How do Rails handle exceptions?
Similar to how Ruby on Rails handles exceptions, so does Ruby. This means we use rescue clauses to specify to Ruby the kinds of exceptions we wish to manage before enclosing any code that might generate an exception in a begin/end block.
Conclusion
In this article, we learned about exception handling in ruby and how we handle exceptions in ruby with the help of rescue methods and classes. I have illustrated some examples to explain the same. That’s all from the article. I hope you all like it.