Say, I want to prevent a divide by 3 anywhere within my current package. Usual procedure is to make an Exception subclass:
class NoDivbyThreeException extends RuntimeException {
public NoDivbyThreeException (String msg) {
super(msg);
}
}
and then throw it where required:
class CustomExceptionDemo {
public static void main(String[] args) {
int numr = 5;
int denr = 3;
try {
if (denr==3) throw new NoDivbyThreeException("Div by 3 not allowed");
else System.out.println("Result: " + numr/denr);
}
catch (NoDivbyThreeException e) {
System.out.println(e);
}
}
}
But what I want is that JVM should prevent a division by 3 anywhere inside this package without my explicit stating of the throw statement inside main(). In other words, the way JVM prevents a divide by zero by throwing exception automatically whenever it encounters such scenario, I want my program to do the same whenever it encounters a divide by 3 situation inside a package.
Is this possible? If not, please elaborate why. That will help to clear my concepts.