In this section, we will learn how to explicitly throw (raise) an exception in Ruby.
Note: we’re assuming you’re already familiar with Ruby Exception Handling.
What is Raise Exception in Ruby? (Explicitly throwing Exception)
So far we know that if you put a malfunction source code in your program or if users enter wrong input data, it can cause the program to raise an exception which might lead to crash if it’s not handled properly!
This raising exception that we’ve seen so far is done by our program automatically! But sometime we might want to explicitly trigger an exception and stop a program from running its usual instructions!
For example, let’s say our program works with files (read their content and print them so that users can see), now we want this program to only work if it’s given a correct type of file! But if it didn’t get an appropriate file, then there’s no point in the program to continue and print the content of the file!
So at this stage it might be appropriate to raise an exception and show an error message to users let them know what was the problem!
Here, Ruby has the tool for us and that’s called `raise`.
The `raise` keyword as the name suggests, is used to raise an exception of a specific type in order to cause a program to start looking for a handler (a rescue clause) that can handle the raised exception.
Ruby raise Operator Syntax:
raise “Reason of the exception” raise ExceptionType , “Reason of the Exception”
As you can see, there are two ways to use the raise keyword and throw exceptions in Ruby:
The first one only takes one string value, which is the reason of why the exception is thrown! So that in the body of a general purpose rescue clause, we can call the `message` method in order to get the mentioned message.
The second way of using the raise keyword is by first declaring the type of exception we want it to be raised, and then adding another value after the exception type to declare the reason of why the exception is raised. This way, the type of the raised exception is clear and so only a specific rescue clause will be called to handle the raised exception.
Example: throwing exception in Ruby using raise operator
def divide (num1 , num2) result = num1 / num2 puts result end puts "Please enter a vlaue: " val1 = gets.to_i puts "Now enter another value: " val2 = gets.to_i begin if val2 == 0 raise ZeroDivisionError, "You can't set the value 0 as the second argument" else divide(val1,val2) end rescue ZeroDivisionError => e puts e.message rescue => e puts e.message end puts "The message after the begin block"
Please enter a vlaue: 20 Now enter another value: 0 You can't set the value 0 as the second argument The message after the begin block