Real-world examples of null reference exception examples explained
Let’s skip the abstract definitions and go straight into concrete examples of null reference exception problems you’ll actually see in modern codebases.
A null reference exception happens when your code tries to use an object that doesn’t exist yet. You call a method, access a property, or index into something that is null (or None, or undefined depending on the language). The best examples are the ones you can recognize instantly in your own project, so we’ll walk through realistic scenarios and then explain how to harden your code.
Classic C# web app: assuming the database always returns a user
One of the most common examples of null reference exception issues in C# web apps comes from authentication or profile pages.
public IActionResult Profile(int id)
{
var user = _dbContext.Users
.FirstOrDefault(u => u.Id == id);
// 💥 Potential NullReferenceException here
var displayName = user.FullName.ToUpper();
return View(model: displayName);
}
If the user with that id doesn’t exist, FirstOrDefault returns null. The next line calls ToUpper() on user.FullName, but user itself is null, so the runtime throws a NullReferenceException.
How to fix it:
if (user == null)
{
return NotFound();
}
var displayName = user.FullName?.ToUpper() ?? "Unknown User";
This is a simple example of null reference exception behavior, but it captures a pattern: never assume your database query found something.
ASP.NET dependency injection gone wrong
Here’s another example of null reference exception examples explained in a modern ASP.NET Core app using dependency injection.
public class EmailController : Controller
{
private readonly IEmailService _emailService;
public EmailController(IEmailService emailService)
{
_emailService = emailService;
}
public IActionResult Send(string to)
{
// 💥 If DI wasn’t configured correctly
_emailService.SendWelcomeEmail(to);
return Ok();
}
}
If IEmailService isn’t registered in Program.cs / Startup.cs, the framework might construct the controller with _emailService as null (or fail earlier, depending on version and configuration). When SendWelcomeEmail is called, you get a null reference exception.
This is one of the best examples for understanding how configuration bugs, not just code bugs, can trigger null reference errors.
Prevention strategies include:
- Enabling nullable reference types (
#nullable enable) so the compiler warns you. - Throwing in the constructor if a required dependency is null.
- Adding integration tests that spin up the app and hit critical endpoints.
For updated .NET guidance on nullability and safety, Microsoft’s docs are still the reference point: https://learn.microsoft.com/en-us/dotnet/csharp/nullable-references
Java Spring Boot: trusting @Autowired a little too much
Java has its own flavor of the same mistake. Consider a Spring Boot service:
@Service
public class OrderService {
@Autowired
private PaymentGateway paymentGateway;
public void processOrder(Order order) {
// 💥 paymentGateway might be null if the bean isn’t created
paymentGateway.charge(order.getCustomerId(), order.getTotal());
}
}
If PaymentGateway isn’t annotated or configured as a Spring bean, paymentGateway can be null at runtime. When charge is called, you get a NullPointerException—Java’s version of a null reference exception.
This is a textbook example of null reference exception examples explained in the Java ecosystem: the framework wiring failed, but the error shows up where you call the dependency, not where it’s misconfigured.
Defensive steps:
- Prefer constructor injection and mark dependencies as
final. - Use static analysis and nullability annotations (
@NonNull,@Nullable). - Add startup tests that assert all required beans are present.
The OpenJDK docs on NullPointerException are still a useful reference: https://docs.oracle.com/javase/8/docs/api/java/lang/NullPointerException.html
Entity relationships: navigation properties that aren’t loaded
ORMs like Entity Framework or Hibernate are a gold mine of real examples of null reference exception surprises.
Imagine a blog system:
var post = _dbContext.Posts
.FirstOrDefault(p => p.Id == id);
// 💥 If Author wasn’t eagerly loaded and lazy loading is off
var authorName = post.Author.Name;
There are two null traps here:
postmight benullbecause the ID doesn’t exist.post.Authormight benullbecause the relationship isn’t set or the navigation property wasn’t loaded.
This is one of the best examples of null reference exception examples explained in data-heavy apps: the object graph isn’t what you think it is.
Mitigation:
- Use
.Include(p => p.Author)when querying. - Enforce required relationships at the database level.
- Add null checks before walking deep object graphs.
Async and background tasks: context disappears, reference goes null
As apps lean harder on async and background processing (especially in 2024+ with more cloud-native designs), null reference bugs increasingly show up in delayed code paths.
Example: a background job processor that pulls messages from a queue.
public class EmailJobHandler
{
private readonly IEmailService _emailService;
public EmailJobHandler(IEmailService emailService)
{
_emailService = emailService;
}
public async Task HandleAsync(EmailJob job)
{
// job.Payload might be null if the message was malformed
var body = job.Payload.Body; // 💥
await _emailService.SendAsync(job.To, body);
}
}
In production, malformed or partially migrated messages are common. job.Payload can be null, but the first time you see the problem is when your job worker crashes at 3 a.m.
This is a subtle example of null reference exception examples explained in distributed systems: you’re trusting external data formats too much.
Hardening tips:
- Validate deserialized messages and reject or quarantine bad data.
- Use nullable reference types and treat warnings as build failures.
- Log defensive checks with enough context to replay the scenario.
For general secure coding and input validation practices, the OWASP guidelines remain a good anchor: https://owasp.org/www-project-top-ten/
JavaScript / TypeScript: undefined is the new null
Even though JavaScript technically uses null and undefined, the pattern is the same. In TypeScript, with strict null checks off, this is a daily occurrence:
interface User {
id: string;
profile?: {
bio?: string;
};
}
function getBio(user: User) {
// 💥 Cannot read properties of undefined (reading 'bio')
return user.profile.bio.toUpperCase();
}
If profile is missing, user.profile is undefined, and trying to access .bio throws at runtime.
This is a very modern example of null reference exception behavior in front-end and Node.js apps. The fix is similar:
function getBio(user: User) {
return user.profile?.bio?.toUpperCase() ?? "No bio";
}
Turn on strictNullChecks in tsconfig.json and you’ll catch a lot of these before they ship.
API integration: trusting third-party responses
In 2024–2025, many bugs come from integrating with external APIs that change behavior under load, error, or new versions. Here’s a realistic C# example:
public async Task<string> GetWeatherSummaryAsync(string city)
{
var response = await _httpClient.GetFromJsonAsync<WeatherResponse>(
$"/weather?city={city}");
// 💥 On API outage or schema change, response or response.Current may be null
return response.Current.Summary;
}
If the remote API returns a 500, an empty body, or a slightly different JSON shape, response or response.Current might be null. You now have a null reference exception wrapped in what looks like a network bug.
This is one of the most instructive examples of null reference exception examples explained for cloud-era apps: the problem isn’t your code logic, it’s your assumptions about someone else’s.
Safer approach:
var response = await _httpClient.GetFromJsonAsync<WeatherResponse>(...);
if (response?.Current == null)
{
_logger.LogWarning("Weather API returned null for {City}", city);
return "Weather data unavailable";
}
return response.Current.Summary;
Mobile apps: lifecycle and null views
In Android or iOS apps, lifecycle events create a steady stream of null reference traps. For example, an Android Fragment:
class ProfileFragment : Fragment() {
private var profileImageView: ImageView? = null
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
profileImageView = view.findViewById(R.id.profileImage)
}
fun updateProfileImage(url: String) {
// 💥 Called after onDestroyView, profileImageView is null
profileImageView!!.load(url)
}
}
If updateProfileImage is triggered after the view is destroyed (for example, due to navigation or rotation), profileImageView is null and the double-bang !! operator throws a NullPointerException.
This is a classic mobile-focused example of null reference exception examples explained: the object used to exist, but the framework reclaimed it.
Safer pattern:
- Use
viewLifecycleOwnerand only update UI when the view exists. - Avoid
!!unless you absolutely know the lifecycle context.
Why null reference exceptions are still common in 2024–2025
You’d think with modern languages and tooling, we’d have fewer of these. But several trends keep them alive:
- Microservices and APIs: More external dependencies means more chances for missing or partial data.
- Async and event-driven systems: Time gaps between events make it easier for objects to disappear between lines of code.
- Schema evolution: Databases and JSON contracts change over time, leaving some fields unset.
- Mixed-language stacks: You might have Kotlin or TypeScript in one layer and legacy Java or JavaScript in another, with different null-safety guarantees.
Static analysis, nullability annotations, and language features have improved, but they only help if teams actually turn them on and treat warnings seriously.
For a broader perspective on software reliability and error handling, university CS courses and materials (for example, MIT OpenCourseWare at https://ocw.mit.edu/) often cover defensive programming patterns that apply directly here.
Patterns to recognize from these examples
Looking across all these real examples of null reference exception behavior, a few patterns repeat:
- Assuming data exists: Trusting that a database row, API field, or JSON property is always present.
- Trusting framework magic: Expecting dependency injection, autowiring, or lifecycle callbacks to always succeed.
- Skipping validation: Using external input (user data, messages, files) without checking for missing fields.
- Ignoring nullable warnings: Treating compiler warnings about nullability as noise instead of early bug reports.
If you train yourself to spot these patterns, you’ll start mentally underlining any line that:
- Walks more than one dot deep (
user.Profile.Address.City). - Accesses anything that came from outside your process.
- Relies on framework configuration you didn’t personally write or test.
These are exactly the kinds of examples of null reference exception examples explained throughout this article.
FAQ: common questions about null reference examples
Q: Can you give another simple example of a null reference exception in C#?
Sure. This is a very short example of how it happens:
string message = null;
Console.WriteLine(message.Length); // 💥 NullReferenceException
You’re calling .Length on a string that doesn’t exist. Even in tiny snippets like this, it matches the same pattern as the larger real examples.
Q: What are common examples of null reference exception causes in production systems?
Common causes include missing database rows, uninitialized services due to configuration mistakes, API responses that omit fields during outages, and background jobs processing malformed messages. All of the best examples in this article map back to one of those root causes.
Q: How do modern languages reduce the risk of these errors?
Languages like Kotlin, Swift, and TypeScript with strict null checks force you to acknowledge nullability in the type system. C#’s nullable reference types do the same. They don’t eliminate every example of null reference exception issues, but they move many of them from runtime to compile time.
Q: Is throwing a null reference exception ever a good idea?
Generally, no. It’s better to validate inputs and throw more specific exceptions (like ArgumentNullException in C#) or to avoid throwing at all by returning error results. Most real examples of null reference exception bugs are accidental, not intentional.
Q: How can teams systematically reduce these errors?
Turn on nullability features, treat warnings as errors in CI, write integration tests around boundaries (database, APIs, message queues), and review pull requests with a specific eye for “what here might be null?” Over time, you’ll see fewer new examples of null reference exception incidents in your logs.
The bottom line: once you’ve seen enough real examples of null reference exception examples explained in context—web controllers, background jobs, mobile views, API integrations—you start to recognize the smell. The next time you’re about to write thing.Property.Method(), pause and ask: What if thing doesn’t exist yet? That tiny habit is still one of the cheapest reliability upgrades you can make.
Related Topics
Real-world examples of null reference exception examples explained
Real-world examples of examples of infinite loop examples in modern software
Real-World Examples of File Not Found Exception Examples in 2025
Real-world examples of database connection failure examples in modern apps
Real-world examples of segmentation fault examples: common runtime errors
Real‑world examples of examples of class not found exception examples
Explore More Runtime Errors
Discover more examples and insights in this category.
View All Runtime Errors