Exception Handling
PS Software Engineering
Some basics
• Exception
–anomalous or exceptional conditions
requiring special processing
• Exception handling
–process of responding to the occurrence
of exceptions; often changing the
normal flow of program execution
• Lisp (1960s,1970s)
[Link]
ehchua@[Link]
Exception & Call Stack
[Link]
ehchua@[Link]
Try – catch - finally
try {
// main logic, uses methods that may throw Exceptions ......
} catch (Exception1 ex) {
// error handler for Exception1 ......
} catch (Exception2 ex) {
// error handler for Exception2 ......
} finally {
// finally is optional
// clean up codes, always executed regardless of exceptions ......
}
void m(){
void p(int b){
… double q(double a, int c){
try{
c = q(1.,b); double d = a/c;
p(1);
… return d;
…
} }
}
catch(Exception e){…}
…
}
void m(){ void p(int b){
… double q(double a, int c){
try{ c = q(1.,b); double d = a/c;
p(0); … return d;
… } }
}
catch(Exception e){…}
…
}
void m(){ void p(int b){
… double q(double a, int c){
try{ c = q(1.,b); double d = a/c;
p(0); … return d;
… } }
}
catch(Exception e){…}
…
}
ArithmeticException
void m(){ void p(int b){
… double q(double a, int c){
try{ c = q(1.,b); double d = a/c;
p(0); … return d;
… } }
}
catch(Exception e){…}
…
}
ArithmeticException
private void importFile() throws IOException {
…
}
private void doSomething() {
if (problem) {
throw new RuntimeException(“Problem Xyz”);
}
}
private void doSomethingElse() {
try {
//can raise a CheckedException
} catch (Exception e) {
throw new RuntimeException(e);
}
}
The try-with-resources statement
(Java >= 7)
static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return [Link]();
}
}
static String readFirstLineFromFileWithFinallyBlock(String path) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(path));
try {
return [Link]();
} finally {
if (br != null) [Link]();
}
}
See [Link]
Example