Академический Документы
Профессиональный Документы
Культура Документы
EXCEPTIONS
Agenda
Understanding exceptions
Syntax
How try/catch/throw works
finally and try-with-resources
Types of exceptions
Effectively using exceptions
Best practices
Stacktraces (how to read them)
Understanding exceptions
Error handling
Programs will encounter errors while
they run (at runtime)
Guaranteed
Whats an error?
Anything that prevents your program to
proceed further: invalid input, missing
input, insufficient resources (memory,
disk space), system errors, etc.
Understanding exceptions
Why? Robustness
Useful programs are resilient to errors
Either handle the errors (alternate route) or
report them (so the user can debug)
Usually programs are composed by multiple
modules (or libraries)
A robust program must take errors into account
when they specify how modules interact
Tell what errors might be reported by the module and for
what reason
Understanding exceptions
Old Way
Throwing an exception
Things to note:
1. The exception itself is just a normal Java object
created with new.
2. Therefore it can have parameters
3. When the program encounters such a statement
the JVM exception handling mechanism takes
control of what will be executed next
Syntax
Catching exceptions
try{
//some code that throws exceptions
}catch(NumberFormatException | IllegalStateException e){
// handle both exceptions
}catch (IllegalArgumentException e){
// handle NPE
}
Things to note:
1. The code that throws exceptions needs to be
surrounded by a try/catch block
2. Different exception types can be handled
independently
3. The order of catch clauses matters
How throw/try/catch works
Exceptions hierarchy
Types of exceptions
Checked vs. Unchecked
throws syntax
//good
boolean verifyCnp(String cnp){
if(cnp == null || cnp.length() != 13) {
throw new IllegalArgumentException("cnp should be exactly 13 digits long");
}
char s = cnp.charAt(0);
//more code to verify
}
Best practices
Configure logging:
Create a file logging.properties
handlers= java.util.logging.FileHandler,java.util.logging.ConsoleHandler
.level=INFO
java.util.logging.FileHandler.pattern=c:/work/sci-exceptions/exceptions.log
java.util.logging.FileHandler.formatter=java.util.logging.SimpleFormatter
try{
//code that reads from a file }
catch(IOException e){
//there is a _very_ good reason I ignore
this IOException: here it is
}
Best practices
void tryBook(){
try{
book();
}catch(BookingCapacityExceededException e){
//handle it
}
}
Booking book(){
if(!isCapacityAvailable()) {
throw new BookingCapacityExceededException();
}
//booking code
}
Best practices
class ContactRepository {
String file;
ContactRepository(String file) { this.file = file; }