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.
Exceptions are just classes that extend class Throwable
. Defining your own exception is done by creating a class that extends Throwable
or one of its subclasses.
You can throw your own exception using throw new myError();
.
ArithmeticException
is a special exception thrown by the JVM when you divide by zero. It's not the exception that is looking for places where you divide by zero; it's how the /
works. The /
operator checks if the denominator is zero and will then throw the exception.
There is no way to add for example a check to the +
operator so that it will throw whatever exception if the result of adding two numbers is zero. You'd have to write your own method to check and do this.
public int add(int a, int b) {
int result = a + b;
if (result == 0) {
throw new myError();
}
return result;
}
// Then use the add() method instead of +
try {
int a = 1;
int b = -1;
int result = add(a, b);
System.out.println(result);
} catch (myError e) {
System.out.println("The result was zero!");
}