How are Exceptions in java defined and how can I define my own?
As an example, we have ArithmeticException which prohibits us dividing by 0 and does not break the program.
What is try-catch's advantage to catching the same potential error with an if-else logic?
Furthermore, suppose I don't operate in the field of all integers, but specifically the field Z2 formed under addition in which 1+1=0.
Provided I have pre-defined an array of logic of operations, were I to do something like this:
try {
int a = 1;
int b = 1;
int c = a/(a+b);
} catch(myError e) {
//
}
where myError :
public class myError extends Exception {
public myError(String e) {
super(e);
}
}
But then, how does the try-catch clause know it is supposed to catch myError? What makes myError be what it is?
In other words: what defines, for example, ArithmeticException, to look for division by 0 among other things?
Alternatively I could throw new myError("something's wrong") , but that would defeat the whole point of defining a "custom" exception to begin with, since I could have thrown any exception like that.
Bank.withdrawMoney(500)withdrawMoney(int n){if(n<0)throw new IllegaArgumentException("You cant withdraw negative number of money");}