Create an exception intentionally

-1

I can create an exception by dividing a value by 0 like this:

try {
    int res = 100/0;
} catch (Exception e){
    Log.wtf(TAG,"Test Exception");
}

But I do not know if that would be the most viable way. How could I exceptionally create an exception? What would be the simplest way to exceptionally create an exception?

    
asked by anonymous 26.03.2017 / 05:32

1 answer

0

Depending on the problem you should "customize" an exception, and it is good practice to help you have better control over your application code.

I'll set up an example to customize an exception for division by zero. The first step is to create a class by extending the exception that most closely resembles your IOException , ArithmeticException problem among others.

public class DivisaoPorZeroException extends ArithmeticException {
    private static final long serialVersionUID = 1L;

    public DivisaoPorZeroException() {
        super();
    }

    public DivisaoPorZeroException(String s) {
        super(s);
    }

}

The second step is to create the method that will effectively perform an operation and where the critical point that will be treated can occur, at this point usually the whole logic of the problem, in this example I used the division by zero, then with the domain of the division technique I will create the method that does only division, taking into account the error that can be found (divide by zero):

public static double dividir(double dividendo, double divisor) throws DivisaoPorZeroException {
        if (divisor == 0) {
            throw new DivisaoPorZeroException("Divisor não pode ser zero");
        }
        return dividendo / divisor;
    }

Now simply testing your result

        System.out.println(dividir(5D, 2D));
        System.out.println(dividir(5D, 0D)); 
    
26.03.2017 / 23:51