Java或C#中异常管理的最佳做法 [英] Best practices for exception management in Java or C#

查看:89
本文介绍了Java或C#中异常管理的最佳做法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被困在决定如何处理我的应用程序中的异常。



如果我的异常问题来自于1)通过远程服务访问数据或2)反序列化JSON对象。不幸的是,我无法保证任何一项任务的成功(切断网络连接,失控我的格式错误的JSON对象)。



因此,如果我遇到异常,我只是在函数内捕获它,并将FALSE返回给调用者。我的逻辑是,所有的调用者真正关心的是如果任务是成功的,不是为什么它不成功。



这里是一些示例代码(在JAVA中)一个典型的方法)

  public boolean doSomething(Object p_somthingToDoOn)
{
boolean result =

try {
//如果脏对象然后清理
doactualStuffOnObject(p_jsonObject);

//假设成功(抛出异常)
result = true;
}
catch(Exception Ex)
{
//不关心异常
Ex.printStackTrace();
}
返回结果;
}

我认为这种方法很好,但我真的好奇知道什么最好的做法是管理异常(我应该真的鼓起一个异常一个调用堆栈吗?)。



关键问题的总结:


  1. 只要捕捉异常,但不要冒泡或正式通知系统(通过日志或向用户发出的通知)可以吗?

  2. 有哪些最佳做法有例外不需要一个try / catch块的一切?

跟进/修改

感谢所有的反馈意见,在网上发现异常管理的一些优秀来源:





似乎异常管理是根据上下文变化的那些事情之一。但最重要的是,应该如何管理系统中的异常情况。



另外要注意通过过多的try / catch或者不给异常的异常(异常是警告系统,还有什么需要被警告的代码)? 。



此外,这是 m3rLinEz 的一个不错的选择


我倾向于同意Anders Hejlsberg,而且,如果操作成功,最多的呼叫者只需
。 / p>

从这个评论中,它提出了一些问题来处理例外情况:




  • 这个异常被抛出什么意思?

  • 如何处理它是有意义的?

  • 呼叫者是否真的关心异常,或者只是关心呼叫是否成功?

  • 强制呼叫者管理潜在的异常优雅吗?

  • 您是否尊重语言的偶像?


    • 你真的需要返回一个成功的标志,如布尔值吗?返回布尔值(或一个int)更多的是C语言,而不是Java(在Java中你将只处理异常)。

    • 跟踪与语言相关的错误管理结构:)!



解决方案

对我来说,你想要捕获异常并将其转换为错误代码似乎是奇怪的。为什么在Java和C#中默认情况下,调用者会偏好错误代码?



对于您的问题:


  1. 你应该只能捕获你实际可以处理的异常。只是
    捕获的异常在大多数情况下不是正确的做法。
    有一些例外(例如,线程之间记录和编组异常
    ),但即使对于那些情况,您通常应该
    重新抛出异常。

  2. 你你的
    代码肯定不会有很多try / catch语句。再次,这个想法只是捕捉你可以处理的异常。
    您可能会包含最大的异常处理程序来将任何未处理的
    异常转换为对最终用户有用的东西,但
    否则您不应该尝试捕获每个
    中的每个异常可能的地方。


I'm stuck deciding how to handle exceptions in my application.

Much if my issues with exceptions comes from 1) accessing data via a remote service or 2) deserializing a JSON object. Unfortunately I can't guarantee success for either of these tasks (cut network connection, malformed JSON object that is out of my control).

As a result, if I do encounter an exception I simply catch it within the function and return FALSE to the caller. My logic is that all the caller really cares about is if the task was successful, not why it is wasn't successful.

Here's some sample code (in JAVA) of a typical method)

public boolean doSomething(Object p_somthingToDoOn)
{
    boolean result = false;

    try{
        // if dirty object then clean
        doactualStuffOnObject(p_jsonObject);

        //assume success (no exception thrown)
        result = true;
    }
    catch(Exception Ex)
    {
        //don't care about exceptions
        Ex.printStackTrace();
    }
    return result;
}

I think this approach is fine, but I'm really curious to know what the best practices are for managing exceptions (should I really bubble an exception all the way up a call stack?).

In summary of key questions:

  1. Is it okay to just catch exceptions but not bubble them up or formally notifying the system (either via a log or a notification to the user)?
  2. What best practices are there for exceptions that don't result in everything requiring a try/catch block?

Follow Up/Edit

Thanks for all the feedback, found some excellent sources on exception management online:

It seems that exception management is one of those things that vary based on context. But most importantly, one should be consistent in how they manage exceptions within a system.

Additionally watch out for code-rot via excessive try/catches or not giving a exception its respect (an exception is warning the system, what else needs to be warned?).

Also, this is a pretty choice comment from m3rLinEz.

I tend to agree with Anders Hejlsberg and you that the most callers only care if operation is successful or not.

From this comment it brings up some questions to think about when dealing with exceptions:

  • What is the point this exception being thrown?
  • How does it make sense to handle it?
  • Does the caller really care about the exception or do they just care if the call was successful?
  • Is forcing a caller to manage a potential exception graceful?
  • Are you being respectful to the idoms of the language?
    • Do you really need to return a success flag like boolean? Returning boolean (or an int) is more of a C mindset than a Java (in Java you would just handle the exception) one.
    • Follow the error management constructs associated with the language :) !

解决方案

It seems odd to me that you want to catch exceptions and turn them into error codes. Why do you think the caller would prefer error codes over exceptions when the latter is the default in both Java and C#?

As for your questions:

  1. You should only catch exceptions that you can actually handle. Just catching exceptions is not the right thing to do in most cases. There are a few exceptions (e.g. logging and marshalling exceptions between threads) but even for those cases you should generally rethrow the exceptions.
  2. You should definitely not have a lot of try/catch statements in your code. Again, the idea is to only catch exceptions you can handle. You may include a topmost exception handler to turn any unhandled exceptions into something somewhat useful for the end user but otherwise you should not try to catch each and every exception in every possible place.

这篇关于Java或C#中异常管理的最佳做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆