簡體   English   中英

C#“如果拋出異常...”

[英]C# "if exception is thrown..."

不確定這是否可能或可能被認為是不好的做法,但我想知道是否有一種很好的方法可以在 C# 中編寫上述if語句。

就像是...

if (method throws exception)
{
    // do something
}
else
{
    // do something else
}

所以你正在尋找的是一個 try catch 語句。 這種結構在許多語言中都很常見,但對於 C# 來說,它非常棒。 我將向您推薦微軟關於 c# 錯誤處理的文檔。 https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/try-catch

這應該教你一切你需要知道的。 對於它在我的術語中的工作原理的簡單概述:

try {
//execute code that you expect to throw an exception
}
Catch (KindOfError ErrorVariable) {
//Error has been thrown, execute code for it.
msgbox.show("Error Raised: " + ErrorVariable.Code.ToString())
}
Finally {
//Execute code here you want to run regardless of error outcome
msgbox.show("This code runs with or without an exception being thrown")
}

這應該能幫到你!

只使用一個普通的 try-catch 塊。 如果拋出異常,它將轉到 catch 塊,如果沒有,它將繼續執行可能拋出異常的方法之后的行。

try
 {
 MethodThatMightThrowException()
 // do something else
 }
catch
 {
 // do something
 }

技術上可以catch異常:

 try { 
   var result = DoSomeAction(arguments);

   /* do something else : result is a valid value*/
 }
 catch (SomeException) {   //TODO: put the right exception type
   /* If exception is thrown; result is not valid */ 

   // throw; // uncomment, if you want to rethrow the exception
 }

但是,您可以實現TryGet模式明確以下if

https://ayoungdeveloper.com/post/2017-03-28-using-the-tryget-pattern-in-csharp/

並將其用作

 if (TryDoSomeAction(arguments, out var result)) {
   /* do something else : result is a valid value*/
 }
 else {
   /* result is not valid; if "exception" is thrown */ 
 }

您可以利用委托並創建一些靜態助手。

在這種情況下,您可以使用ActionFunc 如果您需要從執行的函數中返回一些值,請添加另一個接受Func擴展方法。

public static class SilentRunner
{
    public static void Run(Action action, Action<Exception> onErrorHandler)
    {
        try
        {
            action();
        }
        catch (Exception e)
        {
            onErrorHandler(e);
        }
    }

    public static T Run<T>(Func<T> func, Action<Exception> onErrorHandler)
    {
        try
        {
            return func();
        }
        catch (Exception e)
        {
            onErrorHandler(e);
        }

        return default(T);
    }
}

然后使用它:

SilentRunner.Run(
     () => DoSomething(someObject),
     ex => DoSomethingElse(someObject, ex));

Func情況下,您也可以獲取結果:

var result = SilentRunner.Run(
     () => DoSomething(someObject),
     ex => DoSomethingElse(someObject, ex));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM