Although we have seen the Exceptions provided by Ruby. But sometimes, we need to create our own Exception.
And luckily, Ruby provides an Exception, that you can inherit and define your own exception.
Let us see, how we can achieve with the below example.
class MyException < Exception def initialize() msg = "Number cannot be less than 50" super(msg) end end number = 23 if number < 50 raise MyException.new() end
So, we have defined our custom exception that if a number is less than 50. An exception will be raised.
So, we have created a class called MyException and inherited the Exception class.
The Exception class is defined by Ruby. We will take the help of the Exception class to define our exception class MyException.
class MyException < Exception
In our MyException class, we have defined the initialize() method.
def initialize() msg = "Number cannot be less than 50" super(msg) end
Where we have declared an msg variable and initialised it with the message that needs to be printed when our custom exception occurs.
msg = "Number cannot be less than 50"
The next taks is to pass the message, msg to the Exception class of Ruby.
And we have done it with the super() Method.
super(msg)
And the message, msg goes to the Exception class of Ruby.
And our custom exception class, MyException is ready.
Now, we define a variable number and initialise it with the number 23.
number = 23
Then we have checked, if the value of number is less than 50 or not.
if number < 50 raise MyException.new() end
And in this case the value of number is less than 50. So, our exception class MyException is called, raising the exception using the raise keyword.
raise MyException.new()
And we get the below exception as output.
in `<main>': Number cannot be less than 50 (MyException)
There is also a shortcut to raise a custom exception.
Let us see in the below exception.
if number < 50 raise Exception.new("Number cannot be less than 50") end
So, if you see the above output. We have raised the same exception, without defining a class.
All we have done is called the Exception class of Ruby directly, passing the message, Number cannot be less than 50, using the raise keyword.
raise Exception.new("Number cannot be less than 50")
And we were able to raise our custom exception.