How to create an Exception / Custom Exception in Java

2

Java, brings with it several Exceptions already ready, IllegalArgumentException, IllegalStateException, RuntimeException, among others.

How to create a Custom Exception in Java?

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

Add two integers and prime them to the Output associated with 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 arguments less than zero.

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

  

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

    
asked by anonymous 28.06.2015 / 20:01

1 answer

6

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 the following:

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 an unchecked exception, simply inherit the RuntimeException class instead of Exception

  • In this example we are overwriting both the Exception(String) constructor and Exception(String,Throwable) constructor. Because? Java allows us to chain exceptions, saying that one exception was caused by another exception, the technical term for this case is chaining exceptions . So we need the constructor Exception(String,Throwable) , where throwable is the cause.

  • By inheritance structure both a checked exceptions and unchecked exceptions are serializable objects, that is, they implement the Serializable interface. Therefore, it may be useful to set the serialVersionID field, but not mandatory, the compiler will only throw a Warning.

This question / answer is associated with this one: #

I recommend reading for a complete understanding of Java Exceptions, in case the reader does not know what the terms concade, checked, unchecked mean.

    
28.06.2015 / 20:01