Custom Exceptions

In our restaurant review platform, we need a way to handle errors that are specific to our application's needs.

Understanding Custom Exceptions

Custom exceptions help us communicate domain-specific errors in our application, going beyond the generic exceptions provided by Java.

They allow us to add meaning to our error handling, making it clear what went wrong in the context of our application.

In our case, we want to create exceptions that clearly indicate when something goes wrong with our file storage operations.

Creating a Base Exception

Let's start by creating a base exception that will serve as the parent for all our custom exceptions.

First, create a new package called com.devtiro.restaurant.exceptions.

Here's our base exception class:

package com.devtiro.restaurant.exceptions; public class BaseException extends RuntimeException { public BaseException() { super(); } public BaseException(String message) { super(message); } public BaseException(String message, Throwable cause) { super(message, cause); } }

Notice that we extend RuntimeException rather than Exception.

This choice follows clean code principles, as checked exceptions can break the open/closed principle by forcing changes across multiple layers when new error conditions are added.

Creating the Storage Exception

Building on our base exception, we'll create a specific exception for file storage operations:

package com.devtiro.restaurant.exceptions; public class StorageException extends BaseException { public StorageException() { super(); } public StorageException(String message) { super(message); } public StorageException(String message, Throwable cause) { super(message, cause); } }

This exception will be used in our StorageService when operations like saving or retrieving files fail.

We can now throw this exception with meaningful messages that relate specifically to storage operations:

if (!file.exists()) { throw new StorageException("File not found: " + filename); }

Summary

  • Created a hierarchy of custom exceptions for our application
  • BaseException serves as the parent for all custom exceptions
  • StorageException extends BaseException for file operations
  • Used RuntimeException to avoid checked exception constraints
© 2026 Devtiro Ltd. All rights reserved