Professional Documents
Culture Documents
When running programs, methods can call other methods a large number of times,
therefore forming call chains or call stacks.
● when an exception occurs the normal flow of the program is disrupted and the
program/application terminates abnormally
● (some of these) exceptions must be handled explicitly in code.
Example of exceptions:
● runtime: NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException
● checked: IOException, FileNotFoundException, SQLException
● errors: OutOfMemoryError, StackOverflowError, IOError
Exceptions
● Exceptions in Java = just regular classes but with some specific supertypes
● Exception type (and required handling) - determined by the place in the class hierarchy:
○ Throwable - base class from every “exceptional situation” -> checked
■ Error - a kind of unrecoverable situation, which usually ends in JVM crash (e.g.
out of memory, out of stack due to infinite recursion...) -> unchecked
● note: you should not try to handle/recover from these errors!
- Checked:
- require explicit handling by code:
- need to be declared by methods that might throw them
- need to be handled by caller methods (which call such method which may throw
exceptions), by either:
- catch the exception (to handle it locally)
- or: declare that it will throw it further
- are the ones that do not extend RuntimeException or Error
Since checked exception are the most restrictive, we will refer mostly to them in the following.
try {
//do some work
} catch (Exception e) {
//do something in case of exception
} finally {
//do something, in any case
}
● exceptions can be thrown using the throw keyword on instances of a Throwable class
● methods which may throw a type of (checked) exceptions must declare this in the method’s signature
by using the throws keyword
● thrown exceptions must be handled by the calling method or else further thrown
○ if not handled, the JVM will eventually catch all exceptions (and terminate the thread)
Exceptions - Catching
Exceptions that are thrown by methods can be caught by other methods further down the call stack:
try {
someMethodThrowingExceptions();
} catch (ExceptionType1 | ExceptionType2 e) {
//do something for these exception types
} catch (Exception e) {
//do something for other exception types (still extending Exception), like logging
throw e; //rethrow the caught exception
}
But what if we need something always done, This is where finally comes into play:
even in case of exceptions?
try {
try { fridge.open();
fridge.open(); Eggs eggs = fridge.getEggs();
Eggs eggs = fridge.getEggs(); fridge.close();
fridge.close();
cook(eggs);
cook(eggs);
eat(eggs);
eat(eggs);
} finally {
cleanMess();
} catch (Exception e) { cleanMess();
cleanMess(); }
throw e;
} ● finally block is always executed (with few
possible exceptions)
We should always clean the mess, even when we
● it can be paired up with only a try, if
might have not successfully finished eating!
someone else handles the exception
Exceptions - General Considerations
Rules:
● Declaring thrown exceptions: declared types can be broader than the actually thrown
types (if I throw IOException, I can declare Exception - a supertype - in the signature)
● Overriding: the overriding method must declare that it throws same exceptions as the
base method, or some subtypes of them (can be of a narrower type)
General guidelines:
● Always better to perform some checks, when possible, rather than getting an exception
● Don’t use exceptions for regular control flow, but only for exceptional situations! (avoid
throwing them when not needed / other solutions exist)
● Don’t abuse runtime exceptions, even though they are easier to manage.
Enums
Enums
- An enum type is a special Java data type that allows variables to take values from a
specific set of predefined constants
- The variable must be equal to one of the valid ones defined by the enum
- Because they are constants, they respect the constant Java naming convention
enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}
case FRIDAY:
return "Friday :)"
case SATURDAY:
case SUNDAY:
return "Weekend :D!!!";
default:
return "Midweek days…";
}
}
}
Enums - Examples
enum Planet {
EARTH (5.976e+24, 6.37814e6), An enum can also have properties:
MARS (6.421e+23, 3.3972e6);
● in this case, all values must define
private final double mass; //kg
private final double radius; //meters those properties
● the constructor must have private or
Planet(double mass, double radius) { package-level access
this.mass = mass;
this.radius = radius; ○ you cannot call an enum
} constructor yourself
• devs like to code and when they want to understand a class or operation, they
will first look at a sample code
class DivideTests {
@Test
public void testZeroDividedByAnythingIsZero() {
Assert.assertEquals(0, Main.divide(0, 1));
Assert.assertEquals(0, Main.divide(0, 100));
Assert.assertEquals(0, Main.divide(0, -5));
}
}
● repeat...
Questions?
Extra reading:
https://www.baeldung.com/java-exceptions
https://docs.oracle.com/javase/tutorial/essential/exceptions/
http://tutorials.jenkov.com/java/enums.html
http://users.csc.calpoly.edu/~djanzen/research/TDD08/cdesai/IntroducingJUnit/IntroducingJUnit.html