Chapter 6: Exceptions

Chapter 6: Exceptions · Study Questions
Error typestry and catchfinallytry-with-resourcesHierarchyCheckedthrow and throwsPropagationErrorCustom exceptionStack trace
Sercan KÜLCÜ · Giresun University · Computer Engineering

Output Question · Exception Concept

Question 1: Uncaught Exception

What does the program print? Why is "B" not printed? What do the line numbers in the stack trace show?

public class Division {
  static int f(int[] d) {
    return 10 / (d.length - 2);
  }
  public static void main(String[] args) {
    System.out.println("A");
    System.out.println(f(new int[3]));
    System.out.println(f(new int[2]));
    System.out.println("B");
  }
}
Show answer
A
10
Exception in thread "main"
  java.lang.ArithmeticException: / by zero
    at Division.f(Division.java:3)
    at Division.main(Division.java:8)

(The exception line is a single line on screen; it is split here.)

In the first call, 10 / 1 = 10. In the second the divisor is 0: integer division throws ArithmeticException. Since neither f nor main catches it, the program terminates; line 9 never runs.

The first at is where the exception originated (f, line 3); the one below it is the line that called it (main, 8).

Step-by-Step Trace · try and catch

Question 2: Which catch Runs?

attempt is called with "5", "x", "1", "-2" and "0" in turn. In each call, which block runs and what is printed?

try { parseInt; new int[n]; d[n-1] = 100/(n-1) }catch (ArithmeticException e)catch (RuntimeException e)no exception: catch blocks are skipped

d = new int[5], d[4] = 100 / 4 = 25. Since there is no exception, no catch runs.

try { parseInt; new int[n]; d[n-1] = 100/(n-1) }catch (ArithmeticException e)catch (RuntimeException e)thrown: NumberFormatException

NumberFormatException (line 3) does not match the first catch; since it is a RuntimeException, the second one catches it.

try { parseInt; new int[n]; d[n-1] = 100/(n-1) }catch (ArithmeticException e)catch (RuntimeException e)thrown: ArithmeticException (/ by zero)

n − 1 = 0: in the division, ArithmeticException. The first catch matches; the second is not tried.

try { parseInt; new int[n]; d[n-1] = 100/(n-1) }catch (ArithmeticException e)catch (RuntimeException e)thrown: NegativeArraySizeException

An array cannot be created with a negative size: NegativeArraySizeException, a RuntimeException.

try { parseInt; new int[n]; d[n-1] = 100/(n-1) }catch (ArithmeticException e)catch (RuntimeException e)thrown: ArrayIndexOutOfBoundsException

The index (−1) and the right-hand side (−100) are evaluated; when the index is checked at the assignment, ArrayIndexOutOfBoundsException.

static void attempt(String s) {
  try {
    int n = Integer.parseInt(s);
    int[] d = new int[n];
    d[n - 1] = 100 / (n - 1);
    System.out.println("done " + d[n - 1]);
  } catch (ArithmeticException e) {
    System.out.println("A");
  } catch (RuntimeException e) {
    System.out.println("R " + e.getClass().getSimpleName());
  }
}

Multiple Choice · try and catch

Question 3: catch Order

Which statement is true for this code?

try {
  int s = 10 / 0;
} catch (Exception e) {
  System.out.println("General");
} catch (ArithmeticException e) {
  System.out.println("Arithmetic");
}

A: catch blocks are tried from top to bottom; the Exception block already catches every ArithmeticException, so the second block can never run. The compiler does not allow an unreachable catch. Rule: subclass first, superclass last.

Step-by-Step Trace · finally

Question 4: finally and return

What does the program print? Does finally run before or after return?

trycatch (IllegalStateException e)finallypending return—

f(5): try starts, "T5 " is printed.

trycatch (IllegalStateException e)finallypending return2

return 10 / x: the return value 2 is computed and held; the method has not finished yet.

trycatch (IllegalStateException e)finallypending return2

Before leaving the method, finally runs: "F ".

trycatch (IllegalStateException e)finallypending return—

The pending 2 is returned; println prints it and ends the line.

trycatch (IllegalStateException e)finallypending return—

f(0): "T0 ".

trycatch (IllegalStateException e)finallypending return—

throw: the rest of the try (return 10 / x) is skipped; the division by 0 is never attempted.

trycatch (IllegalStateException e)finallypending return-1

The matching catch prints "C "; return -1 keeps the value pending.

trycatch (IllegalStateException e)finallypending return-1

Again finally: "F ".

trycatch (IllegalStateException e)finallypending return—

−1 is returned. finally ran on both paths, right before the return.

static int f(int x) {
  try {
    System.out.print("T" + x + " ");
    if (x == 0) {
      throw new IllegalStateException();
    }
    return 10 / x;
  } catch (IllegalStateException e) {
    System.out.print("C ");
    return -1;
  } finally {
    System.out.print("F ");
  }
}
// in main
System.out.println(f(5));
System.out.println(f(0));

Multiple Choice · finally

Question 5: When finally Changes the Variable

What does the program print?

static int g() {
  int s = 1;
  try {
    s = 2;
    return s;
  } finally {
    s = 3;
    System.out.print(s + " ");
  }
}
// in main
System.out.println(g());

B: return s; runs, the return value (2) is computed and stored; then finally runs. finally sets s to 3 and prints "3 ", but the stored return value does not change: main prints 2. If finally also contained a return, that value would be returned (not recommended).

Output Question · finally

Question 6: try-with-resources with Two Resources

What does the program print?

class K implements AutoCloseable {
  String name;
  K(String name) {
    this.name = name;
    System.out.println(name + " opened");
  }
  public void close() {
    System.out.println(name + " closed");
  }
}
// in main
try (K a = new K("A"); K b = new K("B")) {
  System.out.println("work");
  throw new RuntimeException("error");
} catch (RuntimeException e) {
  System.out.println("catch " + e.getMessage());
} finally {
  System.out.println("finally");
}
Show answer
A opened
B opened
work
B closed
A closed
catch error
finally

Resources are opened in the order they are written and closed in reverse order: the last one opened is closed first.

Closing happens, even with an exception, before the catch; the catch then runs, and finally runs last.

Output Question · finally

Question 7: Nested try

What does the program print?

try {
  try {
    Object o = "12";
    Integer i = (Integer) o;
    System.out.println("inner try end");
  } catch (NumberFormatException e) {
    System.out.println("inner catch");
  } finally {
    System.out.println("inner finally");
  }
  System.out.println("outer try end");
} catch (ClassCastException e) {
  System.out.println("outer catch");
} finally {
  System.out.println("outer finally");
}
System.out.println("end");
Show answer
inner finally
outer catch
outer finally
end

o is a String object; casting to Integer throws ClassCastException (although "12" looks like a number, no conversion takes place).

The inner catch does not catch this type; while the exception moves outward, the inner finally runs. The rest of the outer try ("outer try end") is skipped, the outer catch catches it, the outer finally runs and the program continues.

Multiple Choice · Exception Hierarchy

Question 8: Which catch Catches It?

new FileReader("missing.txt") throws a FileNotFoundException. Which of the following catch types catches it?

D: A catch catches the written type and all its subclasses. The chain is FileNotFoundException → IOException → Exception → Throwable. RuntimeException and SQLException are separate branches; Error is not part of the Exception family.

Multiple Choice · Exception Types

Question 9: Checked Exceptions

In which group are all of the exceptions checked exceptions?

A: Checked exceptions are those that extend Exception but do not extend RuntimeException; the compiler enforces the “catch or declare” rule. NullPointerException, NumberFormatException and ClassCastException are subclasses of RuntimeException.

Spot the Bug · Exception Types

Question 10: A Read Method That Does Not Compile

Which errors does the compiler give for this method? Write two different fixes.

static String firstLine(String path) {
  BufferedReader r =
      new BufferedReader(new FileReader(path));
  return r.readLine();
}
Show answer
error: unreported exception
  FileNotFoundException; must be caught
  or declared to be thrown
error: unreported exception IOException;
  must be caught or declared to be thrown

FileReader constructor and readLine() throw checked exceptions. 1) Declare it (the caller handles it); the file is also closed:

static String firstLine(String path)
    throws IOException {
  try (BufferedReader r =
      new BufferedReader(new FileReader(path))) {
    return r.readLine();
  }
}

2) Handle it: to the same try-with-resources, catch (IOException e) { return null; } is added and throws is removed. IOException, FileNotFoundException: the former also covers the latter.

Step-by-Step Trace · Throwing Exceptions

Question 11: Propagation of an Exception

In which method does the exception originate, and which lines are skipped? What does the program print?

mainb(1)c(1)

main → b(1) → c(1): three frames.

mainb(1)c(1)

1 > 2 is false; c ends normally and its frame is removed.

mainb(1)c(3)

b calls c a second time: c(3).

mainb(1)c(3)IllegalArgument…

3 > 2: an exception is thrown. c has no try: c ends at that moment, "c done" is not printed.

mainb(1)IllegalArgument…

b has no catch but has a finally: it runs, then the exception path continues. "b done" is skipped.

mainIllegalArgument…

The catch in main matches. "main continues" is skipped.

main

After the catch, the program returns to normal flow.

static void c(int x) {
  System.out.println("c " + x);
  if (x > 2) throw new IllegalArgumentException("x=" + x);
  System.out.println("c done");
}
static void b(int x) {
  try {
    c(x);
    c(x + 2);
    System.out.println("b done");
  } finally {
    System.out.println("b finally");
  }
}
// in main
try {
  b(1);
  System.out.println("main continues");
} catch (IllegalArgumentException e) {
  System.out.println("main: " + e.getMessage());
}
System.out.println("end");

Multiple Choice · Throwing Exceptions

Question 12: throw and Declaration

Which statement is true for this method?

static void f(int x) {
  if (x < 0) {
    throw new Exception("negative");
  }
}

C: Exception (not a RuntimeException) is a checked exception: unreported exception Exception; must be caught or declared to be thrown. Fix: either add throws Exception to the signature, or throw an unchecked type like IllegalArgumentException. throw can be used anywhere in the body (D).

Output Question · Runtime Exceptions

Question 13: Exceptions Line by Line

Each line is run on its own. Which exception is thrown?

1  Object o = "5"; Integer i = (Integer) o;
2  char c = "abc".charAt(3);
3  int n = Integer.parseInt(" 7");
4  int m = Math.addExact(Integer.MAX_VALUE, 1);
5  int g = new ArrayList<Integer>().get(0);
6  int[] d = null; d[0] = 1;
7  int[] e = new int[-1];
Show answer
LineException
1ClassCastException: the object is a String
2StringIndexOutOfBoundsException: valid indices are 0 … 2
3NumberFormatException: leading space
4ArithmeticException: integer overflow
5IndexOutOfBoundsException: size is 0
6NullPointerException
7NegativeArraySizeException

All of them are subclasses of RuntimeException; the compiler requires none of them to be handled. The ordinary + does not throw an exception on overflow; addExact does.

Multiple Choice · Runtime Exceptions

Question 14: A Line Without an Exception

Which of the following expressions, at run time, does not throw an exception?

D: Floating-point division follows the IEEE 754 rules: 10.0 / 0 yields Infinity; there is no exception. Integer division and remainder by 0 give ArithmeticException: / by zero; toIntExact throws, for a value outside the int range, integer overflow.

Multiple Choice · Checked Classes

Question 15: What the Compiler Wants

main: written without try-catch and throws, which one does not compile?

B: Thread.sleep declares that it may throw the checked InterruptedException: unreported exception InterruptedException. The others throw at most an unchecked exception (NumberFormatException, IllegalArgumentException, NullPointerException); the compiler does not check these.

Multiple Choice · Error Classes

Question 16: Infinite Recursion

What happens when the program is run?

static int f(int n) {
  return f(n + 1);
}
public static void main(String[] args) {
  try {
    f(0);
  } catch (Exception e) {
    System.out.println("caught");
  }
  System.out.println("end");
}

C: Each call adds a new frame to the stack; when the stack is full, the JVM throws StackOverflowError. This is an Error; it is not in the Exception family: catch (Exception e) does not catch it, and the program ends with a stack trace. The compiler does not check for infinite recursion.

Coding Question · Custom Exceptions

Question 17: Custom Exception Class

Write a checked InvalidGradeException class and the method int enterGrade(int grade): if the grade is outside 0–100, the exception is thrown with the message "Grade must be 0-100: …"; if it is valid, the grade is returned. What does the loop in main print?

int[] grades = {85, 120, 40};
for (int g : grades) {
  try {
    System.out.println("Saved: "
        + enterGrade(g));
  } catch (InvalidGradeException e) {
    System.out.println("Error: "
        + e.getMessage());
  }
}
Show answer
class InvalidGradeException
    extends Exception {
  InvalidGradeException(String m) {
    super(m);
  }
}
static int enterGrade(int grade)
    throws InvalidGradeException {
  if (grade < 0 || grade > 100) {
    throw new InvalidGradeException(
        "Grade must be 0-100: " + grade);
  }
  return grade;
}
Saved: 85
Error: Grade must be 0-100: 120
Saved: 40

Checked type: throws is required. The try is inside the loop: the error for 120 does not prevent 40.

Output Question · Stack Trace

Question 18: Reading a Stack Trace

What does the program print? According to the stack trace, on which line does the exception originate, where does the null value come from, and why is "done" not printed?

 1 public class School {
 2   public static void main(String[] args) {
 3     int[] a = {70, 80};
 4     int[] b = null;
 5     report("A", a);
 6     report("B", b);
 7     System.out.println("done");
 8   }
 9   static void report(String id, int[] d) {
10     System.out.println(id + ": " + average(d));
11   }
12   static double average(int[] grades) {
13     int t = 0;
14     for (int n : grades) t += n;
15     return (double) t / grades.length;
16   }
17 }
Show answer
A: 75.0
Exception in thread "main"
  java.lang.NullPointerException: …
    at School.average(School.java:14)
    at School.report(School.java:10)
    at School.main(School.java:6)
  • The first at line shows where it originated: average, line 14. The for-each tries to read the length of a null array.
  • Reading downward, the chain is: main (6) → report (10) → average (14). null was assigned to b on line 4 and passed on line 6: fix it where the value is produced.
  • Since nobody caught it, the program terminated; line 7 did not run.

“…”: since Java 14 the message also names the null value.

The End

Chapter 6: Exceptions: Study Questions
Lecture slides: Chapter 6: Exceptions · Lecture notes
1 / 1 Sercan KÜLCÜ. All rights reserved.