Raising Exceptions in Ruby
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. As we know, the code enclosed between begin and end block is totally secured for handling Exceptions and the rescue block tells the ruby, the type of exception is to be handled.
Mainly Runtime Exceptions are handled if they are any error in the code, maybe written by a naive coder, these types of errors may rise “divided by zero error”, “index out of the range error”, etc where the program stops execution whenever these exceptions occur if not handled. By using, raise statement we can raise manual user-defined exceptions. Like, for example, in an ATM transaction program to raise an exception when the user enters an invalid account number to withdraw.
Syntax:
raise exception-type "exception message" condition
Whenever the raise statement is raised it calls the rescue and execution starts from there. raise statement by default raises RuntimeError.
Example :
# Ruby program to illustrate # use of raise statement begin puts 'This is Before Exception Arise!' # using raise to create an exception raise 'Exception Created!' puts 'After Exception' end |
Output :
This is Before Exception Arise! Exception Created!
- Check out the four types of raise statements in the below code:
Example :#!/usr/bin/rubyputs"type-1\n"begin# re-raises the current exception# (RuntimeError as they are no current exception)raiserescueputs'Tony got rescued.'endputs'Tony returned safely'puts"\ntype-2\n"begin# sets this message to the string in the superclass,# this exception will be given top priority in the call stack.raise'Quill got rescued.'puts'quill'# won't executerescueStandardError => eputs e.messageendputs'Quill is back to ship.'puts"\ntype-3\n"begin# uses the first argument to create an exception# and then sets the message to the second argument.raiseStandardError.new'Groot got rescued.'rescueStandardError => e# e=>object# prints the attached string message.puts e.messageendputs"\ntype-4\n"begina =30b =0# here a conditional statement is added# to execute only if the statement is true# raises the exception only if the condition is trueraiseZeroDivisionError.new'b should not be 0'ifb ==0puts a/brescueStandardError => eputs e.messageendputsbegina =30# changing the b value, it passes the raise and executes furtherb =2# raises the exception only if the condition is trueraiseZeroDivisionError.new'b should not be 0'ifb ==0print"a/b = ", a / brescueStandardError => eputs e.messageendOutput:type-1 Tony got rescued. Tony returned safely type-2 Quill got rescued. Quill is back to ship. type-3 Groot got rescued. type-4 b should not be 0 a/b = 15
- Check out the difference between the Runtime and Raised Exception.
Example :#!/usr/bin/rubyputs"Rasied Exception:\n"begina =30b =0# raises the exception only if the condition is trueraiseZeroDivisionError.new'b should not be 0'ifb ==0print"a/b = ", (1+2) * (a / b)rescueZeroDivisionError => eputs e.message# prints the error stack, but a raised exception has zero stackputs e.backtraceendputs"\nRuntime Exception:\n"begina =30b =0x=(1+2) * (a / b)# raises the exception only if the condition is trueraiseZeroDivisionError.new'b should not be 0'ifb ==0print"a/b = ", (1+2) * (a / b)rescueZeroDivisionError => e# prints the message=>(divided by 0)# from ZeroDivisionError classputs e.messageputs e.backtraceendOutput:Rasied Exception: b should not be 0 (repl):8:in `
' /run_dir/repl.rb:41:in `eval' /run_dir/repl.rb:41:in `run' Runtime Exception: divided by 0 (repl):21:in `/' (repl):21:in ` ' /run_dir/repl.rb:41:in `eval' /run_dir/repl.rb:41:in `run' In above example, Runtime Exception has an error stack.


