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. }

  • 相关阅读:
    FileSystemWatcher用法详解【转】
    关于TransactionScope事务的TransactionScopeOption的实例
    TransactionScope IsolationLevel 事务隔离级别
    C#中TransactionScope的使用方法和原理
    关于Qt 静态成员函数调用信号
    【Qt编程】基于QWT的曲线绘制及图例显示操作——有样点的实现功能
    使用qwt作曲线图——有网格线背景的画法
    Qt程序app添加图标复制到其它电脑后不显示的解决方法
    QUrl的使用,特别是对含特殊字符的字符串进行 URL 格式化编码
    QDateTime 本地时间和UTC时间转换问题
  • 原文地址:https://www.cnblogs.com/bjanzhuo/p/3575958.html
Copyright © 2011-2022 走看看