Exceptions

Object -> Throwable -> Exception -> Runtime Exception
Object -> Throwable -> Error

Exception Class Rules
Unchecked exception Runtime exception may be caught, but it is not required that it be caught
Checked exception Class that extends Exception but is not a runtime exception must follow the handle or declare rule where they are either caught or thrown to the caller
Error Error fatal and should not be caught by the program (it is legal to catch it, but not a good practice)

Java (most common) exceptions tree

  • CloneNotSupportedException
  • InterruptedException
  • IOException
    • FileNotFoundException
    • ObjectStreamException
      • NotSerializableException
    • UnsupportedEncodingException
    • FileSystemException
      • FileSystemLoopException
  • SQLException
  • ParseException
  • ReflectiveOperationException
    • ClassNotFoundException
  • RuntimeException
    • ArithmeticException
    • ArrayStoreException
    • ArrayIndexOutOfBounds
    • ClassCastException
    • ConcurrentModificationException
    • DateTimeException
      • DateTimeParseException
    • IllegalArgumentException
    • IllegalStateException
    • IndexOutOfBoundsException
    • NullPointerException
    • NumberFormatException
    • UnsupportedOperationException
    • MissingResourceException

Try statement

Legal vs. illegal configurations

0 finally blocks 1 finally block 2 or more finally blocks
0 catch blocks Not legal Legal Not legal
1 or more catch blocks Legal Legal Not legal

Exceptions rules

  • – illegal to declare a subclass exception in a catch block that is lower down in the list than a superclass exception (unreachable code)
    – compiler will not allow declaration of a catch block for a checked exception type that cannot potentially be thrown by the try clause body (unreachable code)

      • – only checked exceptions that have potential to be thrown may be caught
      – any runtime exception my be caught

    – multi-catch: you cant reassign e variable

Throws vs. Thrown

Throw means an exception is actually being thrown and throws indicate that the method merely has the potential to throw that exception.

public String getDataFromDatabase() throws SQLException { throw new UnsupportedOperationException();
}

Exception constructors

Exception()
Exception(Exception e)
Exception(String message)

Stack trace

try {
throw new CannotSwimException();
} catch (CannotSwimException e) { e.printStackTrace();
}

Multi catch

Syntax:

catch(Exception1 | Exception2 | Exception3 e)
catch(Exception1 e | Exception2 e | Exception3 e) // DOES NOT COMPILE
catch(Exception1 e1 | Exception2 e2 | Exception3 e3) // DOES NOT COMPILE

– multi-catch is to be used for exceptions that aren’t related, compiler prevents you from specifying redundant types in a multi-catch (subtypes)

Try-With-Resources

Idea: automatic resource management (close resources automatically -> finally clause exists implicitly)

Example

public void newApproach(Path path1, Path path2) throws IOException { try (BufferedReader in = Files.newBufferedReader(path1);
BufferedWriter out = Files.newBufferedWriter(path2)) {
out.write(in.readLine()); }
}

– try-with-resources statement is permitted to omit both the catch and finally blocks
– still allowed to have catch and/or finally blocks, they are run in addition to (after)
– resources created in the try clause are only in scope within the try block
– in order for a class to be created in the try clause, it must implement an interface called AutoCloseable and override close() throws Exception
– close method should be idempotent (method can called be multiple times without any side effects or undesirable behavior on subsequent runs)
– AutoCloseable vs. Closable -> close() throws IOException

Suppressed Exceptions

– in TWR, when multiple exceptions are thrown, all but the first are called suppressed exceptions
– loop through suppresed exceptions

for (Throwable t: e.getSuppressed())
System.out.println(t.getMessage());

Assertions

An assertion is a Boolean expression that you place at a point in your code where you expect something to be true. Error (AssertionError) is thrown if the assertion statement results in false.
Syntax:

assert boolean_expression;
assert boolean_expression: error_message

How to enable/disable assertions

java -enableassertions MyClass
java -ea MyClass
java -ea -> enables assertions in all java classes except system classes
java -ea:com.wiley.demos... my.programs.Main -> ... = any class in the specified package or subpackage
java -disableassertions:com.wiley.demos.MyClass my.programs.Main
java -ea:com.wiley.demos... -da:com.wiley.demos.MyClass my.programs.Main

Rules

– assert must be followed by at least one operand and first operand must be boolean
– second operand must evaluate to an object or primitive (it can also be null)
– assertion shouldn’t affects the outcome of the code