1/76
Looks like no tags are added yet.
what do programs assume
everything goes right (open file, read #, use object)
explain david chen case study
financial system try-catch: nothing crashed so everything looked fine
transaction service couldn’t retry/tell the user
crash is bad, running on w/ wrong data worse
crashing vs silently running with bad data
stack trace, know where and when
no message, wrong records written, found weeks later
you should catch an exception..
only where you know what the program does next
helper vs service in catching exceptions
loads an account (can’t know whether to retry or roll back)
runs transaction (knows exactly what those words mean)
exception swallowing
program catches exception but continues execution without logging, processing, or reporting error
often empty/unhelpful catch block
throwable
every problem becomes an object
Java doesn’t print message and hope for best, it builds object
only Throwable can be thrown/caught
throwable family tree
throwable
error (UNCHECKED, DON’T CATCH)
StackOverflowError
OutofMemoryError
NoClassDefFoundError
exception
IOException (CHECKED)
FileNotFoundException
SQLException (CHECKED)
RuntimeException (UNCHECKED)
NullPointerException
ArrayIndexOutOfBoundsException
error: means, example, catch it? and why
JVM in trouble
OutOfMemoryError
no
stopping is safer
exception: means, example, catch it? and why
program hit a condition
FileNotFoundException
yes, where you can act
program can answer it
why not to catch an error
even though compiler lets you, catch block needs memory
catching it turns clean crash into unpredictable one
catch(Exception e) is already wide, catch(Throwable t) is too wide
what does the stack frame hold
main(), which calls run(), which calls load() (top → bottom)
one frame holds params, local variables, and return point
frames pushed on way in, popped on way out
StackOverflowError
recursion w/o base case (nothing to stop it)
frames: recursiveStackOverflowCauser() and 1000s more
NoClassDefFoundError
present at compile time, missing at run time
Main.class still names Helper, but JVM looks and finds nothing
NoClassDefFoundError: family, who asked?, cause, what to do
Error (unchecked)
JVM for compiled code
class missing at run time
fix build or class path
ClassNotFoundException: family, who asked?, cause, what to do
Exception (checked)
your code
by-name lookup failed
must catch or declare it
when JVM lookup fails, ClassNotFoundException appears as…
the “Caused by” under NoClassDefFoundError
four things a program can do instead of crashing
tell user
roll operation back
recover and carry on
cleanly stop
RuntimeException: checked or unchecked
itself & everything below it is UNCHECKED
IOException checked, NullPointerException not
what decides checked/unchecked, and difference between both
compiler
checked = makes you say in advance what you will do
nothing thrown at compile time, compiler just refuses to build
what things are checked/unchecked (basic generalization)
checked: Exception and subclasses except RuntimeException
RuntimeException and below, including errors
what does the compiler demand of a checked exception
handle it
try {…}
catch (IOException e) {..}
or declare it
void load()
throws IOException
do neither and doesn’t compile.
try/catch
execution leaves try block at the throw
try block abandoned at point of throw, not resumed afterwards
how to catch matches (IS-A test)
} catch (IOException e) { runs if thrown object IS-A IOException
IOException subclass of FileNotFoundException
“As a result, FileNotFoundException will be thrown'.” what is actually thrown?
java.io.FileNotFoundException: missing.txt (No such file/directory)
caught by catch (IOException e) bc its IS-A IOException
using the exception object: getMessage() & more
e.getMessage() : detail text, can be null
e.getStackTrace() : full call chain
e.getCause() : earlier exception this one wrapped, if any
reading stack trace
top-down
Line 1: what was thrown and why
each “at”: one frame of stack (who called who)
reading cascading catch blocks
top-down
most specific first
first block whose type matches is one that runs, and is only one that runs
is wrong catch error a compile or runtime error
compile error
multi-catch
one block, several types (Java 7+)
two types must not be related
throws
declaring instead of handling
no try nor catch, and obligation moves to whoever calls it
throw: where, does, looks like, and how many
inside the body / a statement
throws one object, now
throw new X (“…”);
one object
throws: where, does, looks like, and how many
in header after brackets
declares what may come out
… load() throws IOException
as many types as you want
finally
for cleanup (closing files, releasing locks, returning connections)
always runs whatever happened (try succeeded, catch handled it, try or catch returned before value leaves)
how to close a resource correctly by hand
} finally {
if (reader != null) {
try { reader.close(); }
catch (IOException e) { }
}
}what does if (reader != null) {...} check do
close() only runs if file was actually opened
try-with-resources syntax
closed automatically, however block ends
no finally / null check /nested try

what does try-with-resources do
keep original exception
close() throws - attached as suppressed exception
by hand just replaces old expression with new
NullPointerException
reference exists but no object on the other end of it
null
value that means “no object”
runtime exceptions: when to catch it vs fix it?
catch: only at boundary, request handler, or a simple record
fix: everywhere else, should be go-to
defining custom exception class
extends Exception gives you everything Exception already does

throwing and catching custom exception

extends Exception vs extends Runtime Exception
checked, callers must catch or declare it, use when caller can recover
unchecked, callers don’t have to do anything, use when caller made mistake
interfaces vs abstract classes
define capabilities; asks what can this thing DO?
share implementation; asks what IS this thing already?
abstract vs concrete methods
method with a semicolon (what, not how)
method with a body
what can an abstract class contain
abstract methods (signatures w/ no body, for subclasses to complete)
concrete methods (w/ bodies, inherited & usable)
instance fields
constructors (called by subclass w/ super(…)
can an abstract class be instantiated directly
no
how to declare an abstract class
access modifier abstract class class name
ex. public abstract class Cookie
abstract class setup
state
constructor
subclasses need to add own definition
subclasses MAY do x, y, z
access modifiers on abstract members
package-private abstract method: private String, public abstract void
can only be implemented by subclass in SAME package
can abstract methods be private, why or why not
no; nothing could implement it
can abstract classes be instantiated, why or why not
no
abstract = generic object = doesn’t exist
do abstract methods need an abstract class, and vice versa
yes, but abstract classes don’t need to have abstract methods
why do abstract classes have constructors
object’s constructor runs first and sets shared field
class constructor finishes own setup (parent part always built first)
constructor order
parent runs first
who must implement abstract method
inheriting subclass
concrete subclasses forced to implement, abstract can pass it on
abstract classes as types
cannot create a type, but you can declare one
each object runs own method at run time (polymorphism)
how does java fix the diamond problem
Java only allows one parent class
is inheritance of type, behavior, or state allowed and how
yes; one superclass with any number of interfaces
yes (Java 8 and on), default methods carry bodies into implementers
no; only one superclass can contribute instance fields
superclass vs interface
fields, constructor, intialization order
none of the above
interface
contract of what a class must be able to do, w/o explaining how
5 things an interface can contain, since when, and how
constants: Java 1.0; implicitly public static final
abstract methods; Java 1.0; implicitly public abstract
default methods: Java 8; a body inherited by implementers
static methods: Java 8; called on interface itself
private methods; Java 9; helpers for default methods
can interface contain instance variables
no
implicit modifiers in interfaces
you do not type and cannot remove
every interface method is _ whether it is _, _, or _. when is it not?
public; abstract, default, static
only Java 9 private helpers aren’t
implementing methods must be _ and why
public
override can widen access but never narrow it
how to implement interface and is override redundant
use keyword implements
@Override catches misspelled method name at compile time, so not redundant
default methods
every implementer gets default method for free and can override it if specified
why did Java 8 add default methods
adding abstract method to published interface: every implementer breaks
adding default method to published interface: nothing happens
how do default methods conflict and what type of error is it
if the interface bodies disagree; compiler error
how to resolve default method conflict
@Override and decide what to return
extending how many class(es) allows you to implement how many interfaces
one; any number
lambda components (ex. coffee -> coffee.iced )
coffee: parameter, no type needed
→ : given that
coffee.iced : …return this (no return keyword, braces, or class name)
abstract class vs interface: answers what, fields, constructors, how many, instantiable
what IS this thing, real instance state, yes, one per class, no
what can it DO, constants only, never, infinite, no
when to use an abstract class vs interface
shared state/code or a real IS-A
capability, several roles, or loose coupling
can interfaces connect related classes too
yes via implements