如何编写一个try catch语句,需要检查两件事情

huangapple go评论70阅读模式
英文:

How to write a try catch statement where I need to check two things

问题

I have a method which have a try catch clause where I parse a mobile phone number.
如果在解析过程中出现错误,我会进入 catch 语句并引发错误。

All this was OK until I got a request to check for another phone number.
一切都好,直到我收到要检查另一个电话号码的请求。

I am not sure how to do it because later in the code I need at least one correct phone number (its not important which one).
我不确定如何处理,因为在代码后面 我需要至少一个正确的电话号码(哪一个不重要)

If I put both parsing inside one try, I have a problem if first one is wrong and second is good because exception will be raised anyway.
如果我把两个解析都放在一个 try 语句中,如果第一个解析出错而第二个正确,仍然会引发异常。

Maybe something like this? Try inside a catch?
也许可以尝试这样做?在 catch 语句内部再使用一个 try 语句?


<details>
<summary>英文:</summary>

I have a method which have a try catch clause where I parse a mobile phone number.
If parsing goes OK, the code outside the try continues to execute.
If parsing encounters an error, I enter the catch and raise the error.

All this was OK until I got a request to check for another phone number.

I am not sure how to do it because later in the code **I need at least one correct phone number (its not important which one)**.

If I put both parsing inside one try, I have a problem if first one is wrong and second is good because exception will be raised anyway.

try {
model.mobilePhone = PhoneParser.Parse(m.mobile);
model.alternativePhoneNumber = PhoneParser.Parse(m.alternativePhoneNumber);
}

catch (Exception) {
_log.LogWarning("Error while parsing the phone number")
}

return model;


Maybe something like this? Try inside a catch?

try {
model.mobilePhone = PhoneParser.Parse(m.mobile);
}

catch (Exception) {
try {
model.alternativePhoneNumber = PhoneParser.Parse(m.alternativePhoneNumber);
}
catch (Exception) {
_log.LogWarning("Error while parsing the alternative phone number")
}
_log.LogWarning("Error while parsing the mobile phone number")
}

return model;


</details>


# 答案1
**得分**: 1

我建议不要嵌套 try-catch 语句。

对于每个字段(`model.PhoneNumber` 和 `model.AlternativePhoneNumber`),使用两个单独的 try-catch 语句。

尽管解决问题的最佳方法是为电话号码创建一个单独的 `.TryParse()` 扩展方法,并使用它。这也将符合 DRY(不要重复自己)原则。

<details>
<summary>英文:</summary>

I advise against nesting try-catches.

Use two separate try-catches for each field (`model.PhoneNumber` and `model.AlternativePhoneNumber`).

Although the best way of solving your issue would be creating a separate `.TryParse()` extension method for phone number and using that. This would also conform your code to DRY (do not repeat yourself) principle.

</details>



# 答案2
**得分**: 1

If all you need is one valid phone number, create a little helper method in your model called `EnsureValidState`

```csharp
public void EnsureValidState()
{
   if(this.mobilePhone == null &amp;&amp; this.alternativePhoneNumber ==null) 
   {
     //no valid state, raise exception
   }

    //other validation for different rules.
}

Call this method, after all your properties are set and validate accordingly.
You could even abstract this away into an abstract base class for your entities:

public abstract class BaseEntity
{
   private abstract void EnsureValidState();
}

If you want to go a step further have a look at the Hands on DDD example code over at

, that will give you an idea on how to implement a more generic way to ensure consistent updates on your entites and models.

英文:

If all you need is one valid phone number, create a little helper method in your model called EnsureValidState

public void EnsureValidState()
{
   if(this.mobilePhone == null &amp;&amp; this.alternativePhoneNumber ==null) 
   {
     //no valid state, raise exception
   }
    
    //other validation for different rules.
}

Call this method, after all your properties are set and validate accordingly.
You could even abstract this away into an abstract base class for your entities:

public abstract class BaseEntity
{
   private abstract void EnsureValidState();
}

If you want to go a step further have a look at the Hands on DDD example code over at https://github.com/PacktPublishing/Hands-On-Domain-Driven-Design-with-.NET-Core/blob/086cabf75211daa8df9d2117dec0181a0339749d/Marketplace.Framework/Entity.cs, that will give you an idea on how to implement a more generic way to ensure consistent updates on your entites and models.

答案3

得分: 1

The simplest answer is to have two separate try/catch blocks. Otherwise, the alternate phone number will only ever get added if the primary phone number fails (but it's likely that if they supplied both, both are valid).

{
    model.mobilePhone = PhoneParser.Parse(m.mobile);
}
catch (Exception e)
{
    _log.LogWarning($"Error while parsing the mobile phone number:\r\n{e}")
}

try 
{
    model.alternativePhoneNumber = PhoneParser.Parse(m.alternativePhoneNumber);
}
catch (Exception e) 
{
    _log.LogWarning($"Error while parsing the alternative phone number:\r\n{e}")
}

return model;

As others have suggested, implementing a TryParse might be helpful, but then you'll lose the exception information that you're currently logging now. Also, the TryParse should not wrap calls to Parse in try/catch blocks, because exception handling is expensive. Instead it should use the same logic as the Parse method, but return false instead of throwing an exception.

英文:

The simplest answer is to have two separate try/catch blocks. Otherwise, the alternate phone number will only ever get added if the primary phone number fails (but it's likely that if they supplied both, both are valid).

try 
{
    model.mobilePhone = PhoneParser.Parse(m.mobile);
}
catch (Exception e)
{
    _log.LogWarning($&quot;Error while parsing the mobile phone number:\r\n{e}&quot;)
}

try 
{
    model.alternativePhoneNumber = PhoneParser.Parse(m.alternativePhoneNumber);
}
catch (Exception e) 
{
    _log.LogWarning($&quot;Error while parsing the alternative phone number:\r\n{e}&quot;)
}

return model;

As others have suggested, implementing a TryParse might be helpful, but then you'll lose the exception information that you're currently logging now. Also, the TryParse should not wrap calls to Parse in try/catch blocks, because exception handling is expensive. Instead it should use the same logic as the Parse method, but return false instead of throwing an exception.

huangapple
  • 本文由 发表于 2023年3月20日 22:37:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/75791663.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定