在Java中处理异常并不是一个简单的事情。不仅仅初学者很难理解,即使一些有经验的开发者也需要花费很多时间来思考如何处理异常,包括需要处理哪些异常,怎样处理等等。这也是绝大多数开发团队都会制定一些规则来规范对异常的处理的原因。而团队之间的这些规范往往是截然不同的。 本文给出几个被很多团队使用的异常处理最佳实践。 1. 在Finally块中清理资源或者使用try-with-resource语句/ j4 M5 V1 x m( ?) N' C: d $ {1 I# {1 O( Y9 U6 X! _ 当使用类似InputStream这种需要使用后关闭的资源时,一个常见的错误就是在try块的最后关闭资源。 # [) `: O5 K2 u+ [" Y; {public void doNotCloseResourceInTry() {- Y+ `* j& j% L7 m8 { \ FileInputStream inputStream = null;4 u, Q" F: t* i/ O8 a try { File file = new File("./tmp.txt"); inputStream = new FileInputStream(file);- C) y, o, Q, t) m2 E" A5 w // use the inputStream to read a file // do NOT do this inputStream.close();3 @% ?2 U7 W. N) `$ m5 R } catch (FileNotFoundException e) { log.error(e); } catch (IOException e) {5 e8 r9 G$ j d. @! j2 M log.error(e); }- h0 _$ O1 A' ^& C$ S, J$ ? }5 M: V/ s0 M: F 上述代码在没有任何exception的时候运行是没有问题的。但是当try块中的语句抛出异常或者自己实现的代码抛出异常,那么就不会执行最后的关闭语句,从而资源也无法释放。 合理的做法则是将所有清理的代码都放到finally块中或者使用try-with-resource语句。 6 q/ J; [' l/ @ jpublic void closeResourceInFinally() {4 x$ T$ V% u% i6 h; E' h$ H FileInputStream inputStream = null; try { File file = new File("./tmp.txt");* ^3 v7 ]! }5 ], r inputStream = new FileInputStream(file); // use the inputStream to read a file4 F: n% [! @* O" R } catch (FileNotFoundException e) {* @( w, [: S6 y log.error(e); } finally {- p% H$ K2 E3 v if (inputStream != null) {) ~! q# ] J# t0 K( M3 M# Z try {' _1 E) }! K$ c# C) O, P% ` inputStream.close();/ A* [- G' l& Z }' \* c: ` } catch (IOException e) { log.error(e); } }, ^1 h: z- S0 g/ U }/ {! \& v+ ^# `, ~ ?2 {, y } public void automaticallyCloseResource() { Z1 k8 Q+ ?, T) a4 P( B3 j+ I* s File file = new File("./tmp.txt"); try (FileInputStream inputStream = new FileInputStream(file);) { // use the inputStream to read a file } catch (FileNotFoundException e) {1 u" Z5 X0 \) _& O2 |! t log.error(e);4 A8 Y9 N7 W; [3 X2 _8 x [ } catch (IOException e) { log.error(e);6 D% ^+ K9 V3 Z6 B+ a } } 2. 指定具体的异常/ C/ d% `) k3 z+ n9 n8 O + `' L7 d$ ?/ U$ o; i' n, h" \3 R 尽可能的使用最具体的异常来声明方法,这样才能使得代码更容易理解。 : K" {& J! _! G# s& p& @public void doNotDoThis() throws Exception { ...- P3 c* J1 a, U2 e/ N2 [% a, t } public void doThis() throws NumbeRFormatException {/ K% x+ e' H8 r7 \: X7 I ... }2 Z6 O3 M8 N" v% z/ e/ r2 ]6 R 如上,NumberFormatException字面上即可以看出是数字格式化错误。 3. 对异常进行文档说明 4 k9 o$ W7 n: |" ` 当在方法上声明抛出异常时,也需要进行文档说明。和前面的一点一样,都是为了给调用者提供尽可能多的信息,从而可以更好地避免/处理异常。异常处理的 10 个最佳实践,这篇也推荐看下。 7 N$ A! |3 {; J$ S6 Y1 e0 P在Javadoc中加入throws声明,并且描述抛出异常的场景。 3 y6 W+ ^' v8 t3 ]5 J) Q5 u/**+ O2 C0 x1 z( ^ * This method does something extremely useful ...; q, U: ^ m1 \/ M * * @param input8 v1 J# @ P/ x; v2 d * @throws MyBusinessException if ... happens */ public void doSomething(String input) throws MyBusinessException {5 n5 W+ M$ `3 _1 @5 e W; \ ... }$ w5 v; q8 [3 S. ^ 4. 抛出异常的时候包含描述信息 在抛出异常时,需要尽可能精确地描述问题和相关信息,这样无论是打印到日志中还是监控工具中,都能够更容易被人阅读,从而可以更好地定位具体错误信息、错误的严重程度等。 但这里并不是说要对错误信息长篇大论,因为本来Exception的类名就能够反映错误的原因,因此只需要用一到两句话描述即可。 3 m( r8 h+ C) g! t T% `try {& Q/ m8 \: E; W: o- d new Long("xyz"); } catch (NumberFormatException e) { log.error(e); }+ h. z" m; K# B0 _5 g: C NumberFormatException即告诉了这个异常是格式化错误,异常的额外信息只需要提供这个错误字符串即可。当异常的名称不够明显的时候,则需要提供尽可能具体的错误信息。 6 f; L3 `9 u; P4 A% U2 E+ W% k w5. 首先捕获最具体的异常 3 Y. v4 B! M; k7 S- ~$ e1 E 现在很多IDE都能智能提示这个最佳实践,当你试图首先捕获最笼统的异常时,会提示不能达到的代码。当有多个catch块中,按照捕获顺序只有第一个匹配到的catch块才能执行。因此,如果先捕获IllegalArgumentException,那么则无法运行到对NumberFormatException的捕获。 , U; B1 x" [; ?- u$ v, r4 G7 vpublic void catchMostSpecificExceptionFirst() { try { doSomething("A message"); } catch (NumberFormatException e) {5 S u9 \/ W; K6 J% j7 Y) Y log.error(e);7 c- L$ V) Y3 m } catch (IllegalArgumentException e) {! ^! j% K9 f& T9 |( H8 I z log.error(e): p) ^1 s" L! E5 ~: t$ p } }, I Q# B, X# F( q u( K! L4 a! q 6. 不要捕获Throwable 7 {1 ?- }6 o1 Y2 ]' O) J9 E Throwable是所有异常和错误的父类。你可以在catch语句中捕获,但是永远不要这么做。如果catch了throwable,那么不仅仅会捕获所有exception,还会捕获error。而error是表明无法恢复的jvm错误。因此除非绝对肯定能够处理或者被要求处理error,不要捕获throwable。 4 H: ^- z) f# d9 C* _public void doNotCatchThrowable() {6 d1 j* X0 _7 m4 S5 v$ t) Y8 K; W try { // do something } catch (Throwable t) {* I1 R E9 @" ?) Z // don't do this!8 B7 u! l- T7 `/ g0 f0 }) O- B } } 7. 不要忽略异常; v' D+ p1 O& e . H. R2 h3 @) J- i# l+ Q/ U 很多时候,开发者很有自信不会抛出异常,因此写了一个catch块,但是没有做任何处理或者记录日志。 - V! E J) E hpublic void doNotIgnoreExceptions() {% H% a4 \ R* E& b% t" c+ O. _) O try {% ~. T# n+ w7 p' Y* i5 S- u7 g* U // do something+ v) G2 [. ]8 I/ s! |' t! @ } catch (NumberFormatException e) { r: X# L' u. g$ s. ~* ~ // this will never happen } }4 L: D9 d- c7 [0 K! s: U) j& ] 但现实是经常会出现无法预料的异常或者无法确定这里的代码未来是不是会改动(删除了阻止异常抛出的代码),而此时由于异常被捕获,使得无法拿到足够的错误信息来定位问题。合理的做法是至少要记录异常的信息。 0 Q y+ c3 E- B. apublic void logAnException() {9 D) D. @ B: e5 L. }8 [ try { // do something. y$ H+ h& R: [4 |) b) G4 b } catch (NumberFormatException e) {! f# n' V9 F, p; n+ p. v log.error("This should never happen: " + e); }. M' k6 e* x2 I3 i } 8. 不要记录并抛出异常 ( G# u% D) n6 |4 n3 { 可以发现很多代码甚至类库中都会有捕获异常、记录日志并再次抛出的逻辑。如下: try {% A+ ~0 t! x# C- u9 D new Long("xyz");/ Z1 l1 ?$ g L) F0 l7 F } catch (NumberFormatException e) {! h# o- d4 x7 q( H# ]7 f log.error(e);3 M# ?) Q H) G( l# }, V" q9 \+ @5 x throw e;* B7 |- n! h: Z w: S } 这个处理逻辑看着是合理的。但这经常会给同一个异常输出多条日志。如下: 17:44:28,945 ERROR TestExceptionHandling:65 - java.lang.NumberFormatException: For input string: "xyz"% c8 t% V S& K& U+ l9 D% v Exception in thread "main" java.lang.NumberFormatException: For input string: "xyz"- B9 G- `2 b2 A- K. w8 Y1 j at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)4 c* t$ |/ j- W8 W7 [ at java.lang.Long.parseLong(Long.java:589)& o1 ~% E1 f/ P3 n5 X" d at java.lang.Long.(Long.java:965) at com.stackify.example.TestExceptionHandling.logAndThrowException(TestExceptionHandling.java:63) at com.stackify.example.TestExceptionHandling.main(TestExceptionHandling.java:58) 如上所示,后面的日志也没有附加更有用的信息。如果想要提供更加有用的信息,那么可以将异常包装为自定义异常。 : q) i# z5 M$ [- o; opublic void wrapException(String input) throws MyBusinessException { try { // do something } catch (NumberFormatException e) { throw new MyBusinessException("A message that describes the error.", e);# h: {/ L" v1 W3 q } }& k5 M. i. c7 p/ q S 因此,仅仅当想要处理异常时才去捕获,否则只需要在方法签名中声明让调用者去处理。 9. 包装异常时不要抛弃原始的异常# N/ M+ ]$ d6 Y( v* [. D2 U4 t/ o 捕获标准异常并包装为自定义异常是一个很常见的做法。这样可以添加更为具体的异常信息并能够做针对的异常处理。 . Q" V, f/ D/ w. j' t需要注意的是,包装异常时,一定要把原始的异常设置为cause(Exception有构造方法可以传入cause)。否则,丢失了原始的异常信息会让错误的分析变得困难。 public void wrapException(String input) throws MyBusinessException {. e w7 x- J$ v6 w/ ~ try { // do something } catch (NumberFormatException e) { throw new MyBusinessException("A message that describes the error.", e); } }* X J$ ]% {9 m0 g Z. t 总结 综上可知,当抛出或者捕获异常时,有很多不一样的东西需要考虑。其中的许多点都是为了提升代码的可阅读性或者api的可用性。异常不仅仅是一个错误控制机制,也是一个沟通媒介,因此与你的协作者讨论这些最佳实践并制定一些规范能够让每个人都理解相关的通用概念并且能够按照同样的方式使用它们。 |
关于我们|手机版|EDA365电子论坛网 ( 粤ICP备18020198号-1 )
GMT+8, 2025-8-19 21:18 , Processed in 0.109375 second(s), 27 queries , Gzip On.
地址:深圳市南山区科技生态园2栋A座805 电话:19926409050