Could someone explain me when it is useful to use the keyword throw new .. instead of using throws next to the signature of a method ?
I know that when a method throws a Checked Exception. Java forces us to deal with it by doing it directly in the method by handling the Exception into a try-catch bloc or by specifying that it will be done elsewhere with the keyword throws next to the signature.
However, I have some trouble to understand when it is useful to use the keyword throw new and why. Is it related with handling Unchecked Exceptions ?
For instance in this example. Why don't we throw new ArithmeticException() in the method compute ? Since ArithmeticException is an unchecked one ? Should we not add something like :
private static int compute(int i) { if(i == 0) { throw new ArithmeticException(); } return 1/i; } .
public class Main { public static void main(String[] args) { for (int i = -2; i < 2; i++) { try { System.out.println(i+" -> "+compute(i)); } catch (ArithmeticException e) { System.out.println(i+" -> undefined") } } } private static int compute(int i) { return 1/i; } }