Mastering Custom Exceptions in Java: A Step‑by‑Step Guide

This tutorial explains how to define, implement, and throw custom Java exceptions, providing complete example code, step‑by‑step creation instructions, and a practical demo that integrates the custom exception into a JSON‑processing method.

FunTester
FunTester
FunTester
Mastering Custom Exceptions in Java: A Step‑by‑Step Guide

When writing test scripts, developers often need custom exceptions to signal specific error conditions; Java makes it straightforward to create both checked and unchecked exception classes.

Creating a Custom Exception Class

The following example defines a simple custom exception named FailException that extends Exception. It includes a default constructor that calls super("FunTester") and a protected constructor that accepts a custom message.

package com.fun.base.exception;

public class FailException extends Exception {
    private static final long serialVersionUID = -7041169491254546905L;

    public FailException() {
        super("FunTester");
    }

    protected FailException(String message) {
        super(message);
    }
}

Key steps to create the exception:

Create a Java class.

Extend the Exception class.

Invoke super() in the constructor.

Throwing the Custom Exception

Below is a static helper method that throws the custom exception with a supplied message.

public static void fail(String message) {
    throw new FailException(message);
}

Steps to trigger the exception:

Instantiate the FailException (via the helper method).

Use the throw keyword.

Declare the exception with throws in the method signature when necessary.

Demo: Using the Custom Exception in a JSON Utility

The following method parses a JSON response, using FailException.fail to abort when the content is empty. It demonstrates typical try‑catch‑finally handling and how the custom exception integrates with existing logic.

private static JSONObject getJsonResponse(String content, JSONObject cookies) throws FailException {
    JSONObject jsonObject = new JSONObject();
    try {
        if (StringUtils.isEmpty(content))
            FailException.fail("Response is empty!");
        jsonObject = JSONObject.parseObject(content);
    } catch (JSONException e) {
        jsonObject = getJson("content=" + content, "code=" + TEST_ERROR_CODE);
        logger.warn("Response body is not JSON, automatically converted to JSON!");
    } finally {
        if (cookies != null && !cookies.isEmpty())
            jsonObject.put(HttpClientConstant.COOKIE, cookies);
        return jsonObject;
    }
}
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaBackend DevelopmentException HandlingProgramming tutorialcustom-exception
FunTester
Written by

FunTester

10k followers, 1k articles | completely useless

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.