我们可以在一种方法中抛出异常并在另一种方法中处理它吗?



我有两种方法,其中方法 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 中捕获它。请从中帮助我。

My 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)
    { 
    }
}

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。

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

最新更新