public static void fibonacci(String[] args)
{
try
{
int lo = 1;
int hi = 1;
int n = Integer.parseInt(args[0]);
System.out.println(lo);
for (int i = 1; i < n; i++)
{
System.out.println(hi);
int temp = hi;
hi = lo + hi;
lo = temp;
}
}
catch (ArrayIndexOutOfBoundsException e)
{
System.err.println("No command line argument provided");
}
catch (NumberFormatException e)
{
System.err.println("Command line argument " + e.getMessage() + " is not an integer");
}
finally
{
System.out.println("Done!");
}
}
Specifying exceptions
public static void fibonacci(String[] args) throws ArrayIndexOutOfBoundsException, NumberFormatException
{
int lo = 1;
int hi = 1;
int n = Integer.parseInt(args[0]);
System.out.println(lo);
for (int i = 1; i < n; i++)
{
System.out.println(hi);
int temp = hi;
hi = lo + hi;
lo = temp;
}
}
Throwing exceptions
public static void fibonacci(String[] args) throws ArrayIndexOutOfBoundsException, NumberFormatException
{
int lo = 1;
int hi = 1;
if (args.length == 0)
{
   
throw new ArrayIndexOutOfBoundsException();
}
int n = Integer.parseInt(args[0]);
// may still throw a NumberFormatException
System.out.println(lo);
for (int i = 1; i < n; i++)
{
System.out.println(hi);
int temp = hi;
hi = lo + hi;
lo = temp;
}
}
Interfaces
Question
AException and BException are both subclasses of
Exception. Furthermore, BException is a subclass
of AException. Draw the inheritance diagram. Is an
AException object of type BException? Is a
BException object of type AException?
method may throw exceptions of type AException
and BException. Are the following code fragments valid?
If so, do they always produce the same output?
try try
{ {
method(); method();
} }
catch (AException e) catch (BException e)
{ {
System.out.println("A"); System.out.println("B");
} }
catch (BException e) catch (AException e)
{ {
System.out.println("B"); System.out.println("A");
} }