Rails RecordNotFound Exception Handling

Rails RecordNotFound exception occurs when there is error while fetching records from database. RecordNotFound is one of the Exception Handling class provided by Rails.

1. What is RecordNotFound Exception:

It is Exception class defined in the


errors.rb file which comes with your Rails.

2. When RecordNotFound Exception is thrown:

Code Snippet of file errors.rb mentioned above -

# Raised when Active Record cannot find record by given id or set of ids.
class RecordNotFound < ActiveRecordError

ActiveRecordError class is inherited from StandardError class which is subclass of Exception class. Thus ultimately Exception is superclass of StandardError class.

Sample code to reproduce the exception:

Suppose you have users table in your database, thus model User in codebase. And you try to fetch record by following code:


And your database don’t have user with id 1234352, then it will throw error as,

ActiveRecord::RecordNotFound: Couldn't find User with ID=1234352

As mentioned in above snippet, it is thrown when ActiveRecord can not find record in the database that you are trying to fetch.

Basically, record with corresponding fields in your where clause doesn’t exist in the database.

3. Exception Handling for RecordNotFound Exception:

You can handle this exception as,

// your code to fetch the database details from table
rescue RecordNotFound => e
// puts 'Handled RecordNotFound Exception'


In this tutorial, we have seen what is Rails RecordNotFound exception and how to handle it in the codebase when we try to fetch records from the database.


Akshay Mohite

Hi there! I am a Ruby on Rails & ReactJS Enthusiast, building some cool products at DTree Labs.

Read More
Buy me a coffee