java 异常机制

 实践:

1.通过try catch捕获异常,可以给调用者友好提示

例如controller里面遇到异常,如果不抛出就会出现500错误给浏览器。如果在controller中捕获异常,那么就可以友好的提示了,例如:

 1     /**
 2      * 通用下载请求
 3      * 
 4      * @param fileName 文件名称
 5      * @param delete 是否删除
 6      */
 7     @GetMapping("common/download")
 8     public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request)
 9     {
10         try
11         {
12             if (!FileUtils.isValidFilename(fileName))
13             {
14                 throw new Exception(StringUtils.format("文件名称({})非法,不允许下载。 ", fileName));
15             }
16             String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
17             String filePath = Global.getDownloadPath() + fileName;
18 
19             response.setCharacterEncoding("utf-8");
20             response.setContentType("multipart/form-data");
21             response.setHeader("Content-Disposition",
22                     "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, realFileName));
23             FileUtils.writeBytes(filePath, response.getOutputStream());
24             if (delete)
25             {
26                 FileUtils.deleteFile(filePath);
27             }
28         }
29         catch (Exception e)
30         {
31             log.error("下载文件失败", e);
32         }
33     }
View Code

 

2.如果自己不能处理,可以抛出异常,

java 关键字

try、catch、throw、throws 和 finally

try catch :语句用于捕获并处理异常

finally: 语句用于在任何情况下(除特殊情况外)都必须执行的代码---- 此关键字,笔试题的时候,经常遇到。debug会发现,先运行finally里面的代码,然后执行return方法 https://blog.csdn.net/jdfk423/article/details/80406297

throw: 语句用于拋出异常

throws: 语句用于声明可能会出现的异常。

posted @ 2021-07-08 09:50  wullll  阅读(58)  评论(0)    收藏  举报