How to create a custom Exception/Exception in Java

Asked

Viewed 19,133 times

5

Java, brings with it several ready-made Exceptions, Illegalargumentexception, Illegalstateexception, Runtimeexception, among others.

Creating a Custom Java Exception?

I have the following method - sumAndPrint(int,int)

Sum two integers and print them to the Output associated with the System.

public void sumAndPrint(int x, int y) throws Exception{
        if(x < 0 || y < 0){
            //trocar uma excessao específica - NumeroNegativoException
            throw new Exception("Numeros negativos nao permitidos");
        }
        System.out.println("soma -> " + (x+y));
    }

However, I do not accept as arguments values less than zero.

I want to create my own exception(checked Exception) - NumeroNegativoException - how do I do that?

The purpose of this question/answer is to share knowledge about how to create exceptions in Java.

  • 2

    Do not create exceptions just because you want a more specific name. In the case of your example use IllegalArgumentException because that’s what it’s all about.

  • This issue has the purpose of sharing knowledge of how to create . This is just an @ramaral example

  • Tip: "Exception" is spelled "ç", not "ss".

1 answer

8


Creating custom exceptions in Java is perfectly possible, and this practice is widely used by many frameworks, such as Hibernate, Spring, Struts and many others.

The language for creating Exceptions is as follows:

class NumeroNegativoException extends Exception  /* RuntimeException */{
    /**
     * importante caso a exceção seja serializada
     */
    private static final long serialVersionUID = 1149241039409861914L;

    // constrói um objeto NumeroNegativoException com a mensagem passada por parâmetro
    public NumeroNegativoException(String msg){
        super(msg);
    }

    // contrói um objeto NumeroNegativoException com mensagem e a causa dessa exceção, utilizado para encadear exceptions
    public NumeroNegativoException(String msg, Throwable cause){
        super(msg, cause);
    }
}

Important points:

  • To create the same exception above, but as a Runtimeexception, also called unchecked Exception, simply inherit the Runtimeexception class to the instead of Exception

  • In this example we are overwriting both the builder Exception(String) how much Exception(String,Throwable). Why? Java allows us to string together exceptions, saying that an exception was caused by another exception, the technical term for this case is chaining exceptions. That’s why we need the builder Exception(String,Throwable), where Throwable is the cause.

  • By inheritance structure both a checked exceptions and an unchecked exceptios are serializable objects, i.e., implement the interface Serializable. Therefore, it may be useful to define the field serialVersionID, but not mandatory, the compiler will only release a Warning.

This question/answer is associated with this other: Exceptions in Java

I recommend reading for a complete understanding of Exceptions in Java if the reader doesn’t know what the terms chaining, checked, unchecked mean.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.