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

  • 相关阅读:
    【整理】PHP获取客户端真实IP地址详解
    配置百度编辑器变成纯代码编辑器
    Notepad++安装SVN插件
    【CodeBase】【转】php随机生成汉字
    【CodeBase】PHP打印所有用户自定义常量
    php5.3新垃圾回收机制详解
    php脚本cli 模式运行
    php 内存分配新
    php-fpm epoll封装
    火焰图定位dbproxy问题
  • 原文地址:https://www.cnblogs.com/bjanzhuo/p/3575958.html
Copyright © 2011-2022 走看看