Creating a custom exception type
suggest changeA 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:
ConnectionErrorDontPanicError
When the name is already clear, you don’t need the Error suffix, because it would be redundant:
FileNotFoundvsFileNotFoundErrorDatabaseExplodedvsDatabaseExplodedError
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents