Creating a custom exception type

suggest change

A custom exception is any class that extends Exception or a subclass of Exception.

In general, extend StandardError or a descendant. The Exception family is usually for virtual-machine or system errors. Rescuing Exception can swallow Interrupt and stop a forced exit from working as expected.

# Defines a new custom exception called FileNotFound
class FileNotFound < StandardError
end

def read_file(path)
  File.exist?(path) || raise(FileNotFound, "File #{path} not found")
  File.read(path)
end

read_file("missing.txt")  #=> raises FileNotFound, "File missing.txt not found"
read_file("valid.txt")    #=> reads and returns the content of the file

It’s common to name exceptions by adding the Error suffix at the end:

When the name is already clear, you don’t need the Error suffix, because it would be redundant:

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents