Create an exception on purpose

Asked

Viewed 205 times

-1

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

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

But I don’t know if it would be the most viable way. How could I possibly create an exception on purpose? What would be the simplest way to create an exception purposefully?

  • 2

    Try using the Exception class throw new Exception("Test Exception");

  • 2

    throw new ArithmeticException("divisão por 0...");

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 put together an example to customize an exception for division by zero. The first step is to create a class extending the exception that most resembles your problem IOException, ArithmeticException 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 dealt with can occur, at this point usually is the whole logic of the problem, in this example I used the division by zero, then with the command of the division technique I will create the method that makes only the division, taking into account the error that can be found (divided 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)); 

Browser other questions tagged

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