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));
Try using the Exception class
throw new Exception("Test Exception");
– viana
throw new ArithmeticException("divisão por 0...");
– itscorey