Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby's Exception Error classes

Tags:

ruby

You can create a subclass of an exception to make it more descriptive, but how should you set the default 'message'?

class MyError < StandardError   # default message = "You've triggered a MyError" end  begin   raise MyError, "A custom message" rescue Exception => e   p e.message end  begin   raise MyError raise Exception => e   p e.message end 

The first should output 'A custom message'

The second should output 'You've triggered a MyError'

Any suggestions as to best practice?

like image 452
JP. Avatar asked Aug 01 '10 16:08

JP.


People also ask

What is exception class 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. In Ruby, descendants of an Exception class are used to interface between raise methods and rescue statements in the begin or end blocks.

How do you handle exceptions in Ruby?

Ruby also provides a separate class for an exception that is known as an Exception class which contains different types of methods. The code in which an exception is raised, is enclosed between the begin/end block, so you can use a rescue clause to handle this type of exception.

What is the class exception?

The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch. The class Exception and any subclasses that are not also subclasses of RuntimeException are checked exceptions.

What is standard error in Ruby?

StandardError is a superclass with many exception subclasses of its own, but like all errors, it descends from the Exception superclass. StandardErrors occur anytime a rescue clause catches an exception without an explicit Exception class specified.


1 Answers

Define an initialize method, which takes the message as an argument with a default value. Then call StandardError's initialize method with that message (using super).

class MyError < StandardError   def initialize(msg = "You've triggered a MyError")     super(msg)   end end 
like image 62
sepp2k Avatar answered Sep 23 '22 16:09

sepp2k