is this correct way to use try catch block

时间:2015-07-28 15:39:06

标签: c# try-catch except

I wanted to throw an exception if something went wrong in the method resubmit()

 var manager = new ApprovalsDashboardManager();        
    try
    {
        manager.Resubmit(requestId, userId);
    }
    catch (Exception e)
    {

        throw new ApplicationException("Resubmit Request Failed, Please resubmit in a while", e.InnerException);
    }

Is his correct way of using try catch block and I wanted to know how to error handle methods which are in other project being called in my current project.

3 个答案:

答案 0 :(得分:1)

Syntactically, yes, this is the correct way to use a try-catch block. However, if you have access to the code, I would suggest modifying the ApprovalsDashboardManager.Resubmit() method so that it throws your custom ApplicationException when something goes wrong. It's a little redundant to catch an exception just to throw another exception.

EDIT: However, it is not "bad practice" to do this. This use-case is included in the MSDN page for try-catch. https://msdn.microsoft.com/en-us/library/0yd65esw.aspx

答案 1 :(得分:0)

If your "ReSubmit" function is throwing the exception, you don't need to throw it again. It is acceptable to handle the exception simply by providing some information to the user about what happened.

So you would do this somewhere in the catch. You did right by adding some more information into the exception's Message, this is good practice.

答案 2 :(得分:0)

正如您所做的那样,包装异常的问题在于它倾向于隐藏错误的真正来源,因为堆栈跟踪反映了引发异常的点。这有所缓解,因为您已将原始异常包含为InnerException

如果您隐藏了实现细节并且不希望通过异常向用户公开这些细节,那么这可能是合法的事情。但是,例外的用户通常是开发人员,您可以更好地提供更准确和详细的信息。

我也很警惕抓住所有例外情况。例如,如果您收到OutOfMemoryException会发生什么?你真的想忽略它吗?如果您不知道如何处理内存不足,那么最好让异常泡到一个其他代码可能知道如何处理的下一个级别。

相关问题