Exception和IOException之间的使用区别

时间:2023-03-08 23:08:41
Exception和IOException之间的使用区别

Exception和IOException之间的使用区别

先看一段代码.这段代码来自《深入剖析tomcat》

 
 public void await() {
// 创建ServerSocket对象
InetAddress add = null;
ServerSocket ss = null;
try {
add = InetAddress.getByName(LOCAL);
ss = new ServerSocket(port, blocklog, add);
} catch (IOException e) {
e.printStackTrace();
}
// 如果URI是/SHUTDOWN说明需要关闭服务器
Socket s = null;
InputStream in = null;
OutputStream out = null;
// 进入循环,知道响应完成
while (!shutdown) {
try {
//接收socket并创建流
s = ss.accept();//只会在8080端口接收到一个HTTP请求的时候才返回
in = s.getInputStream();
out = s.getOutputStream();
// 创建Request对象并parse,获取资源uri
Request request = new Request(in);
request.parse();
// 创建Response对象并执行操作
Response response = new Response(out);
// 传入Request对象,根据getUri()获取uri地址并进行加载
response.setReqest(request);
response.sendStaticResource();
// 关闭socket,同时输入流和输出流自动关闭
s.close();
// 检查返回的URI是否是服务器关闭命令
shutdown = request.getUri().equals(SHUTDOWN_COMMAND);
} catch (Exception e) {
e.printStackTrace();
//出现异常就继续重新接收
continue;
}
}
}

在这里用的是Exception而不是IOException,这里使用Exception是为了保证捕获异常后可以继续维持JVM的运行.如果Exception换成IOException后,一旦出现IO异常,便会捕获停止运行.

下面是运行结果(Exception)
Exception和IOException之间的使用区别

如果抛出的是IOException

Exception和IOException之间的使用区别 
明显看出后者导致JVM停止