![]() |
VOOZH | about |
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 :
Output :
This is Before Exception Arise! Exception Created!
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
Raised 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'