public class Fraction {
private int num;
private int den;
Fraction (int num, int den) {
this.num = num;
this.den = den;
reduce();
}
}
What stops us from calling new Fraction(1, 0)
?
Unique problem:
new Fraction(1, 0)
Exceptions give a way of:
Fraction (int num, int den) throws ArithmeticException {
if (den == 0) {
throw new ArithmeticException("division by zero");
}
this.num = num;
this.den = den;
reduce();
}
When throw ...
is executed, method call halts
return
statement, but nothing returned; no Fraction
creatednew Fraction(1, 0)
throws the exceptionWhen an exception is thrown it can be caught
Fraction f;
try {
// some code that could throw an exception
f = newFraction(getNum(), getDen());
} catch (ArithmeticException e) {
// code to be executed if exception is thrown
System.out.println(e);
System.out.println("Using default value of 0/1");
f = newFraction(0, 1);
}
try-catch
block
InputStream in
System.in
in.read()
returns one character at a time from terminal input
int
0
through 255
represents char
-1
represents end of streamIOException
if something goes wrong123
, -23
represent numbersMammoth
, 12a3
don’t represent numbersWrite a program that
1 yes 2 no -321
int
in.read()
to get individual charactersint
value?Implement solution with no exception handling first