1

我有两种方法,其中方法 1 抛出异常。方法 2 调用方法 1,如果它抛出异常应该在方法 2 中处理。

这是我的方法1

 private Customer GetCustomer(string unformatedTaxId)
        {
            if (loan.GetCustomerByTaxId(new TaxId(unformatedTaxId)) == null)
            {
                throw new NotFoundException("Could not find the customer corresponding to the taxId '{0}' Applicant address will not be imported.", new TaxId(unformatedTaxId));

            }

            return loan.GetCustomerByTaxId(new TaxId(unformatedTaxId));
         }

现在在以下方法中,我正在调用方法 1

public void ProcessApplicantAddress(ApplicantAddress line)
        {
            try
            {
                Customer customer = GetCustomer(line.TaxId);


                Address address = new Address();
                address.AddressLine1 = line.StreetAddress;
                address.City = line.City;
                address.State = State.TryFindById<State>(line.State);
                address.Zip = ZipPlusFour(line.Zip, line.ZipCodePlusFour);
              }
              catch(NotFoundException e)
            {
                    eventListener.HandleEvent(Severity.Informational, line.GetType().Name, e.Message);
            }

我的问题是我得到一个未处理的异常,但我应该在方法 2 中捕获它。请帮助我。

我的 NotFoundException 类

//  class NotFoundException


  public class NotFoundException : Exception
    {



    public NotFoundException() : base() 
    { 
    }


    public NotFoundException(string message): base(message) 
    { 
    }


    public NotFoundException(string format, params object[] args): base(string.Format(format, args)) 
    { 
    }

    public NotFoundException(string message, Exception innerException) : base(message, innerException) 
    { 
    }


    public NotFoundException(string format, Exception innerException, params object[] args) : base(string.Format(format, args), innerException)
    { 
    }
}
4

2 回答 2

0

Try-Catch 块是相对昂贵的操作,它们会使调试变得困难。我强烈建议您避免使用带有 try-catch 的错误处理模式。相反,您可以跳过抛出并检查 null 的方法:

public void ProcessApplicantAddress(ApplicantAddress line)
{

    var customer = loan.GetCustomerByTaxId(new TaxId(line.TaxId));

    if (customer == null)
    {
        eventListener.HandleEvent(Severity.Informational, "ApplicantAddress", String.Format(""Could not find the customer corresponding to the taxId '{0}' Applicant address will not be imported."", line.TaxId));
    }
    else
    {
        var address = new Address();
        address.AddressLine1 = line.StreetAddress;
        address.City = line.City;
        address.State = State.TryFindById<State>(line.State);
        address.Zip = ZipPlusFour(line.Zip, line.ZipCodePlusFour);
        //do whatever else you need to do with address here.
    }
}

您最初发布的代码应该可以工作,但我猜 GetCustomerByTaxId 在找不到客户时会抛出自己的异常。您可能会考虑单步执行该方法并确保在找不到客户时它实际上会返回 null。

于 2013-09-05T17:17:18.167 回答
0

throw永远不会被触发,因为在 if 语句中执行的函数引发了另一个异常,所以 catch 不会被触发,因为它是另一种类型的异常。

于 2013-09-05T17:18:46.003 回答