Catch the exception and throw the same thing?

Could you please tell me which approach is better in two code blocks?

catch (MyException e) {
    throw new MyException ("Error processing request", e);
}

      

or

catch (MyException e) {
    throw e;
}

      

+2


source to share


7 replies


To compare the two approaches, they must do the same. These two don't do the same thing .

The first approach will be better because you will change its message to be more user-friendly. Perhaps you could also write it down (stack trace or something ...) before throwing it away.

The second approach is better in terms of performance. In fact, it would be even better if you didn't catch the exception at all and let it throw you.



You should choose which is preferable based on user experience and possibly logging or performance. By default (and not always) I would choose the former .

Hope I helped!

+2


source


Keep the inner exception and I have no problem. Although, I don't think it makes sense to catch and then be reborn. Surely it would be better to just throw a custom exception?



0


source


You can save anyway StackTrace

, no problem. But it must be complete, there is no point in catching and throwing the same thing Exception

.

0


source


I see no point in catching the exception and throwing it again. A once rare scenario might be that you need to perform some operation when an exception occurs, but at the same time report the exception to the caller in order to take appropriate action.

If so, then the first approach is better because you are throwing the same exception again (instead of creating a new one). Btw, both approaches will preserve the stack trace , just the point is to avoid creating an unnecessary object first .

For example:

catch (MyException e) {
  // May be perform some clean-up activity and throw
    throw new MyException ("Error processing request", e);
}

      

0


source


You can wrap the original exception as in the first option if you want to include any additional useful information for the calling methods.

0


source


The first, because the second approach (throwing the same exception without any handling) is useless.

Usually you need to define how to handle the exception when starting the project. Will you be using checked or unchecked exceptions? Will you be using standard or custom exceptions? How will you use exception inheritance? Where will you handle (log) exceptions? What information should be passed in exceptions. Once you've answered these questions, it's time to start building your API.

0


source


You can also save the caught exception and provide additional information. The base Exception class has an InnerException. In my example, ExceptionMessage captures the state of some variables that are hidden deep in the structure and would not be obvious in a normal stack trace. Catching the exception, adding extra information, can get the best of both worlds, as both stacks above and below the throw are preserved.

        public override void LoadData()
    {
        string ExceptionMessage = $"ExceptionMessage -> LoadData(){Environment.NewLine}";
        _viewBalancesOnLoad = null;
        try
        {
            ExceptionMessage += $"@visit, the _appointment reference is {NullText(_appointment)}.{Environment.NewLine}";
            var visitDeposit = getOrCreateCopayDeposit("Visit", out _viewBalancesOnLoad);
            var visitPDO = new PrmDataObject(visitDeposit);
            var testDeposit = this.DataObject.GO as Deposit;
            ExceptionMessage += $"@visit, testDataObject is {NullText(testDeposit)}, _deposit.IsComplete = {testDeposit.IsComplete}, and _deposit.IsCreated = {testDeposit.IsCreated}.{Environment.NewLine}";
            this._controlVisitPayment.InitDOControl(visitPDO);

            ExceptionMessage += $"@account, location, the _appointment reference is {NullText(_appointment)}.{Environment.NewLine}";
            var accountDeposit = getOrCreateCopayDeposit("Account", out _viewBalancesOnLoad);
            var accountPDO = new PrmDataObject(accountDeposit);
            testDeposit = this.DataObject.GO as Deposit;
            ExceptionMessage += $"@account, testDataObject is {NullText(testDeposit)}, _deposit.IsComplete = {testDeposit.IsComplete}, and _deposit.IsCreated = {testDeposit.IsCreated}.{Environment.NewLine}";
            this._controlAccountPayment.InitDOControl(accountPDO);

            if (Financials.IsSiteToSite() == true)
            {
                ExceptionMessage += $"IsSiteToSite{Environment.NewLine}";
                string append = " (Master Server Connection)";
                if (this._groupBoxVisitPayment.Text.Contains(append) == false) // can get reloaded
                {
                    this._groupBoxVisitPayment.Text += append;
                    this._groupBoxAccountPayment.Text += append;
                }
            }
        }
        catch(Exception innerException)
        {
            ExceptionMessage += $" <- ExceptionMessage{Environment.NewLine}";
            Exception ne = new Exception(ExceptionMessage,innerException);
            throw ne;
        }
    }

      

0


source







All Articles