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));