Updated April 3, 2023
Introduction to Ruby Exceptions
In Ruby to handle unexpected conditions, we can use the begin rescue, here unexpected means the situation which can create a problem for the execution of code. For example, if you are calling server to fetch data from database and database is down or table deleted etc in these type of situation we cannot do anything with code but to display a proper error message we need to use begin and catch and we need to know proper exception class for a given situation. In many situations like calling other server applications if the server is down execution, our application can be halted so to avoid such type of situations we use begin and rescue in Ruby, we can use it either with default begin and end or with the try-catch keyword itself.
Exceptions Classes in Ruby
Any error which occurs in Ruby always belongs to some exception classes. We can also use try to deal with the exception, let us take an example, simply if we wanted to read a file (because it is possible that file may not be there) and the file was not there then there will be an exception which needs to handle otherwise further execution of the code is not possible (file not available belongs to one exception class). We take one more example for better clarity in a case dealing with the SQL queries as it is possible that the table may be deleted and if it fails to execute further. So the Exceptions in Ruby for many types like it may be because of the wrong syntax, it may be because of the wrong operation, etc. There are many exceptions in Ruby.
Given below are various exceptions classes in ruby with an example:
1. Interrupt
Interrupt is a class that halts the execution from there and starts the previous code to execute. See the below example where we are simply taking a blank json inside the loop and here the whole code is inside the begin block which will check for any exception and if any rescue will play its role with help of Interrupt.
Example:
Putting code block in begin and inside rescue, we are getting the data related to an exception.
Code:
begin
puts "We are printing here moment"
loop {}
rescue Interrupt => e
puts "Here we are looking to the Interrupt exception class"
end
Output:
2. StandardError
This is a very common exception class in Ruby, which can display the details of the occurred exception. See in the below example where we are trying to open a file anyfile.rb which does not exist the directory and an exception generated for it. Here the name of the exception is LoadError.
Example:
Code:
require 'anyfile.rb' rescue "Hi"
Output:
3. ArgumentError
This error exception occurs when the argument provided is not correct. Many times when you call any function at that time the function can have some arguments, and there will be some exceptions if the number of arguments is not matching. See in the below example here we are passing the wrong number of arguments.
Example:
Code:
["ranjan","vijay","ajay"].first(4, 5)
Output:
4. KeyError
In case of any has(object) if the search key is not there in the given hash then this error will occur as the exception class keyError. See in the below example here we are creating an object with name funcData and assigning some key value pair to it. At the time of searching the element finalFunc, if it is not there it will display an error of exception keyError.
Example:
Code:
funcData = {"testFunc" => :finalFunc}
funcData.fetch("testFunc") #=> :finalFunc
funcData.fetch("finalFunc") #=> KeyError: Here it will raise key not found error
Output:
5. IndexError
This is similar to key error, this exception occurs in case of Array. In case we are trying to fetch an index of an array and if that index is not available then this type of error occurs. See in the below example here we have created an array indexData and assigned some array attributes to it. We tried to search various index it was giving result but once we fetch for the index which was not available here, it displayed an error of exception IndexError.
Example:
Code:
indexData = [:a, :b, :c]
indexData.fetch(2) #=> :b
indexData[4] #=> nil
indexData.fetch(4) #=> IndexError: As we can see the Array it does not have element number 4 as its maximum size is less than 4
Output:
6. IOError
Here we are trying to read the directory /test/host reading gets failed then an exception of error class with name IOError will be generated. See in the below example here we are trying to open the directory /test/host.
Example:
Code:
File.open("/test/hosts") {|f| f.close; f.read }
Output:
7. ENOENT
When we are trying to read a file and that file is not available then these types of exception classes are generated. See in the below example we are trying to read a file anyfile.rb, but this file does not exist here so the output of exception will be ENOENT.
Example:
Code:
File.open("anyfile.rb")
Output:
8. SyntaxError
These type of exception classes generally you will face in Ruby while doing coding and you will miss some syntax, see the below example we are writing unnecessary = here which does not make any sense hence we got an exception error class with name SyntaxError.
Example:
Code:
eval("11+1=20"+2)
Output:
Conclusion
From this tutorial we learned about the exception of Ruby and learned about the exception classes of Ruby, we learned the places where these classes of exception can be used in real life with help of some important examples, we gone through the many important exception classes with the reason of those exception classes.
Recommended Articles
We hope that this EDUCBA information on “Ruby Exceptions” was beneficial to you. You can view EDUCBA’s recommended articles for more information.