🌐
Javatpoint
javatpoint.com › custom-exception
Java Custom Exception - javatpoint
Java Custom Exception. If you are creating your own Exception that is known as custom exception or user-defined exception.Let's see example of custom exception.
🌐
Baeldung
baeldung.com › home › java › core java › create a custom exception in java
Create a Custom Exception in Java | Baeldung
May 11, 2024 - try (Scanner file = new Scanner(new ... the root cause of the exception. To fix this, we can also add a java.lang.Throwable parameter to the constructor....
🌐
Tutorialspoint
tutorialspoint.com › java › java_custom_exception.htm
Java - Custom Exception
Here is the syntax to create a custom class in Java - ... You just need to extend the predefined Exception class to create your own Exception. These are considered to be checked exceptions. Keep the following points in mind when writing your own exception classes − · All exceptions must ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › user-defined-custom-exception-in-java
User-Defined Custom Exception in Java - GeeksforGeeks
There are two types of custom exceptions in Java. Checked Exceptions: It extends the Exception class. and it must be declared in the throws clause of the method signature.
Published   August 14, 2025
🌐
Alvin Alexander
alvinalexander.com › java › java-custom-exception-create-throw-exception
Java: How to create and throw a custom exception | alvinalexander.com
As you can see, all you need to do to throw your custom exception is (1) create a new instance of the exception (new AlsCustomException("Anything but zero ...")), and then (2) throw that exception with the throw keyword. With those two pieces in place, we'll create a "driver" class with a main ...
🌐
JetBrains
blog.jetbrains.com › idea › 2024 › 03 › easy-hacks-how-to-throw-java-exceptions
Easy Hacks: How to Throw Java Exceptions | The IntelliJ IDEA Blog
March 12, 2024 - By making information about potential exceptions available, any caller can decide what to do with the exception: ignore it by adding a throws to the method signature or catch the exception and handle it.
🌐
Medium
medium.com › @salvipriya97 › custom-exceptions-in-java-301ef3b568a3
Custom Exceptions in Java. What is a Custom Exception? | by Priya Salvi | Medium
February 13, 2024 - A custom exception in Java is essentially a user-defined exception class that extends either Exception (for checked exceptions) or RuntimeException (for unchecked exceptions).
🌐
Tpoint Tech
tpointtech.com › custom-exception
Custom (User-Defined) Exception in Java - Tpoint Tech
It allows developers to signal that an error has occurred and needs to be handled. The thrown exception must be an instance of Throwable or one... ... In Java, using a try block inside another try block is permitted. It is called as nested try block. Every statement that we enter a statement ...
Find elsewhere
🌐
Medium
medium.com › @nweligalla › creating-custom-exceptions-in-java-ea77a61fcaf4
Creating Custom Exceptions in Java | by Nayana Weligalla | Medium
January 31, 2024 - This amount is sent to the parent class’s constructor with a concatenated string using super(). Because you’re overriding the default Java constructor with one that takes an amount parameter, you can also create another no-args constructor and use it to throw an exception directly. if you want you can call the super() without any parameters. You don’t have to only extend the Exception class; you can also extend the RuntimeException for your custom exception.
🌐
BeginnersBook
beginnersbook.com › 2013 › 04 › user-defined-exception-in-java
User defined exception in java
*/ MyException(String str2) { str1=str2; } public String toString(){ return ("MyException Occurred: "+str1) ; } } class Example1{ public static void main(String args[]){ try{ System.out.println("Starting of try block"); // I'm throwing the custom exception using throw throw new MyException("This ...
🌐
Javatpoint
javatpoint.com › throw-keyword
Java Throw Keyword - javatpoint
Java Throw exception. The Java throw keyword is used to explicitely throw an exception. Let's see its example.
Top answer
1 of 9
274

You should be able to create a custom exception class that extends the Exception class, for example:

class WordContainsException extends Exception
{
      // Parameterless Constructor
      public WordContainsException() {}

      // Constructor that accepts a message
      public WordContainsException(String message)
      {
         super(message);
      }
 }

Usage:

try
{
     if(word.contains(" "))
     {
          throw new WordContainsException();
     }
}
catch(WordContainsException ex)
{
      // Process message however you would like
}
2 of 9
131

You need to create a class that extends from Exception. It should look like this:

public class MyOwnException extends Exception {
    public MyOwnException () {

    }

    public MyOwnException (String message) {
        super (message);
    }

    public MyOwnException (Throwable cause) {
        super (cause);
    }

    public MyOwnException (String message, Throwable cause) {
        super (message, cause);
    }
}

Your question does not specify if this new exception should be checked or unchecked.

As you can see here, the two types are different:

  • Checked exceptions are meant to flag a problematic situation that should be handled by the developer who calls your method. It should be possible to recover from such an exception. A good example of this is a FileNotFoundException. Those exceptions are subclasses of Exception.

  • Unchecked exceptions are meant to represent a bug in your code, an unexpected situation that you might not be able to recover from. A NullPointerException is a classical example. Those exceptions are subclasses of RuntimeException

Checked exception must be handled by the calling method, either by catching it and acting accordingly, or by throwing it to the calling method. Unchecked exceptions are not meant to be caught, even though it is possible to do so.

🌐
Rollbar
rollbar.com › home › how to throw exceptions in java
How to Throw Exceptions in Java | Rollbar
2 weeks ago - You now have the tools to throw, declare, and create custom exceptions in your Java applications.
🌐
Hero Vired
herovired.com › home › learning-hub › topics › custom-exceptions-in-java
How to Create Custom Exceptions in Java - Hero Vired
In this example, InvalidUserInputException is thrown when the input is invalid. It makes the code easy to read and understand. Handling file operations can get tricky. What if a file doesn’t exist? A custom exception can help here, too. import java.io.File; class FileProcessingException extends Exception { public FileProcessingException(String message) { super(message); } } class FileHandler { public void readFile(String filePath) throws FileProcessingException { if (!new File(filePath).exists()) { throw new FileProcessingException("File not found: " + filePath); } // File processing logic } } public class Main { public static void main(String[] args) { FileHandler handler = new FileHandler(); try { handler.readFile("nonexistent.txt"); } catch (FileProcessingException e) { System.out.println(e.getMessage()); } } }
🌐
Stackify
stackify.com › java-custom-exceptions
Implement Custom Exceptions in Java: Why, When and How
May 1, 2023 - That’s all you need to do to implement a custom checked exception. You can now throw the MyBusinessException in your code, specify it as part of your method signature and handle it in a catch clause.
🌐
CodeJava
codejava.net › java-core › exception › how-to-create-custom-exceptions-in-java
How to create custom exceptions in Java
It’s a common practice for catching a built-in exception and re-throwing it via a custom exception. To do so, let add a new constructor to our custom exception class. This constructor takes two parameters: the detail message and the cause of the exception.
🌐
Scaler
scaler.com › topics › custom-exception-in-java
Java Custom Exception - Scaler Topics
November 23, 2022 - Custom exceptions, subclasses of ... error management. Creating a custom exception in Java involves extending the base Exception class and utilizing the throw keyword to raise instances when needed....
Top answer
1 of 1
3

Lets make a custom ResourceAlreadyExistsException class . It will extends the RuntimeException class, and you can add as many parameters to it as you like. I've kept it concise like this.

public class ResourceAlreadyExistsException extends RuntimeException {

    public ResourceAlreadyExistsException(String property, String value) {
        super(String.format(
            "Resource with property %s and value %s already exists." +
            "Make sure to insert a unique value for %s",
            property, value, property));
    }
}

Whenever I need to check for a unique resource, I can tell the user which specific property has what value that causes the error. Furthermore, I notify the user what action must be taken to avoid the error.

Say, I chose to use error *** for my ResourceAlreadyExistsException. Still, I need to hook up this error message to the ExceptionResponseHandler. The extra method is very similar to the method that we usually create for handling all exceptions. In fact, you can easily copy-paste this method for all the exceptions you have. All you have to do, is changing the Exception class to your exception and change the HttpStatus..

@ExceptionHandler(ResourceAlreadyExistsException.class)
public final ResponseEntity<ExceptionResponse> handleResourceAlreadyExistsException(
    ResourceAlreadyExistsException ex, WebRequest req) {
    ExceptionResponse exceptionResponse = new ExceptionResponse(
        new Date(),
        ex.getMessage(),
        req.getDescription(false)
    );
    return new ResponseEntity<>(exceptionResponse, HttpStatus.UNPROCESSABLE_ENTITY);
🌐
Vultr Docs
docs.vultr.com › java › examples › create-custom-exception
Java Program to Create custom exception | Vultr Docs
December 16, 2024 - The method declares that it might throw this type of exception by using the throws keyword. Sometimes, you might want to include more context or functionality in your custom exception class.