zoukankan      html  css  js  c++  java
  • java common practice to rethrow exceptions

    New comer to Java may throw exception in the wrong way, and the net outcome of that is very misleading error message, which can cause the user of the libraries very confused. so it is very vital to keep the exception right.

    One common case of dealing message is when you are dealing calls from a lower library and you may guard against potential damage from the down-stream and throw domain specific exceptions. that menas you may need to rethrow exception in cases.

    But it is easy to get it wrong. by wrong, it often meaning that the original stack is destroyed on the way to propagate to the final consumer. Let 's do a comparison on the following code.

    Let 's see the code below

    Java代码 复制代码 收藏代码
    1. package Syntax.rethrow;
    2. import java.lang.UnsupportedOperationException;
    3. import java.lang.Exception;
    4. public class Rethrow {
    5. public static void generateException() {
    6. throw new UnsupportedOperationException();
    7. }
    8. public static void rethrowException() throws Exception{
    9. try {
    10. generateException();
    11. } catch (Exception ex) {
    12. // you cannot swallow it
    13. throw new Exception("Caught an exception", ex);
    14. }
    15. }
    16. public static void rethrowExceptionDestroyOriginalCallstack() {
    17. try {
    18. generateException();
    19. } catch (Exception ex) {
    20. throw ex;
    21. }
    22. }
    23. public static void main(String[] args) {
    24. try {
    25. rethrowException();
    26. } catch (Exception ex) {
    27. ex.printStackTrace();
    28. }
    29. System.out.println("-=========================");
    30. try {
    31. rethrowExceptionDestroyOriginalCallstack();
    32. } catch (Exception ex) {
    33. ex.printStackTrace();
    34. }
    35. }
    36. }

  • 相关阅读:
    MVC5+EF6 入门完整教程11--细说MVC中仓储模式的应用
    MVC5+EF6 入门完整教程十
    MVC5+EF6 入门完整教程九
    MVC5+EF6 入门完整教程八
    MVC5+EF6 入门完整教程七
    MVC5+EF6 入门完整教程六
    MVC5+EF6 入门完整教程五
    MVC5+EF6 入门完整教程四
    MVC5 + EF6 完整入门教程三
    从前端的UI开始
  • 原文地址:https://www.cnblogs.com/bjanzhuo/p/3575958.html
Copyright © 2011-2022 走看看