Exception
- An Exception indicates conditions that a reasonable application might want to catch.
- An Error indicates serious problem that a reasonable application should not try to catch:StackOverflowError, Both Error and Exceptions extend from Throwable
Checked Exception
- Exceptions other than Runtime Exception. Must use either try/ catch block or throws
try {
FileInputStream fs = new FileInputStream("./a.txt");
} catch (FileNotFoundException e) {
System.out.println("catch...");
e.printStackTrace();
} finally {
System.out.println("finnaly...");
}
// leave it to JVM
public class ExceptionTest {
public static void execute() throws Exception {
System.out.println("execute...");
throw new Exception();
}
public static void main(String[] args) throws Exception {
execute();
}
}
- Multiple catch: Subclass must be before superclass
New forms in Java 7
- Try with resources
和python里 “with open() as f:” 一样
static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader bt = new BufferedReader(new FileReader(path))) {
return br.readLine();
}
}
catch (IOException | SQLException) {
logger.log(ex);
throw ex;
}
// duplicated code elimitated!