Java Reference
In-Depth Information
Ideally programs execute without generating any errors, but in practice various
problems arise. If you ask the user for an integer, the user may accidentally or per-
haps even maliciously type something that is not an integer. Or your code might have
a bug in it.
The following program always throws an exception because it tries to compute the
value of 1 divided by 0, which is mathematically undefined:
1 public class CauseException {
2 public static void main(String[] args) {
3 int x = 1 / 0;
4 System.out.println(x);
5 }
6 }
When you run the program, you get the following error message:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at CauseException.main(CauseException.java:3)
The problem occurs in line 3, when you ask Java to compute a value that can't be
stored as an int . What is Java supposed to do with that value? It throws an exception
that stops the program from executing and warns you that an arithmetic exception
occurred while the program was executing that specific line of code.
It is worth noting that division by zero does not always produce an exception. You
won't get an exception if you execute this line of code:
double x = 1.0 / 0.0;
In this case, the program executes normally and produces the output Infinity .
This is because floating-point numbers follow a standard from the Institute of
Electrical and Electronics Engineers (IEEE) that defines exactly what should hap-
pen in these cases, and there are special values representing infinity and "NaN" (not
a number).
You may want to throw exceptions yourself in the code you write. In particular, it
is a good idea to throw an exception if a precondition fails. For example, suppose that
you want to write a method for computing the factorial of an integer. The factorial is
defined as follows:
n ! (which is read as “ n factorial”)
1 * 2 * 3 * ... * n
You can write a Java method that uses a cumulative product to compute this result:
public static int factorial(int n) {
int product = 1;
for (int i = 2; i <= n; i++) {
 
Search WWH ::




Custom Search