Exception
Definition: An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.
the checked exception
比如,java.io.FileNotFoundException
the error
比如,java.io.IOError
the runtime exception
比如,NullPointerException
error和runtime exception又叫做unchecked exception
Catching and Handling Exceptions
try {
code
}
catch and finally blocks . . .
try {
} catch (ExceptionType name) {
} catch (ExceptionType name) {
}
使用|
catch多个:
catch (IOException|SQLException ex) {
logger.log(ex);
throw ex;
}
finally
The finally block always executes when the try
block exits.
it allows the programmer to avoid having cleanup code accidentally bypassed by a return
, continue
, or break
.
finally {
if (out != null) {
System.out.println("Closing PrintWriter");
out.close();
} else {
System.out.println("PrintWriter not open");
}
}
finally一定会被执行,除非在try或catch的时候JVM退出了。
The Try-with-resources Statement
为了确保资源被回收,可以使用try-with-resources,类似于Python的with语句:
static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br =
new BufferedReader(new FileReader(path))) {
return br.readLine();
}
}
Any object that implements java.lang.AutoCloseable
, which includes all objects which implement java.io.Closeable
, can be used as a resource.
OkHttp的示例代码就用到了try-with-resources语句:
OkHttpClient client