c#程式設計最佳實踐1:異常處理
阿新 • • 發佈:2021-02-05
—
你是否在使用者輸入驗證中使用異常處理機制?
如果是,那麼你就是那個把你的專案執行速度降低了62倍的人。你不相信我嗎?等幾分鐘;我來教你怎麼做。但是在這個例子之前,讓我們瞭解一下在什麼地方需要異常處理。
例如,你正在驗證使用者的資料,對於任何無效的輸入,你將引發一個異常並將其丟擲給客戶端,如下所示:
class BusinessLogcCheck
{
public void Check()
{
try
{
//Your validation code is here
}
catch (Exception ex)
{
throw new Exception("My own exception");
}
}
}
親愛的朋友,在下一個示例中,如果你看到輸出螢幕,你將意識到這種做法有多糟糕。讓我們看看下面的程式碼。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.NetworkInformation;
namespace Test1
{
class Program
{
public static void ThrowTest()
{
throw new Exception("This is exceptopn");
}
public static Boolean Return()
{
return false;
}
static void Main(string[] args)
{
Stopwatch sw = new Stopwatch();
sw.Start();
try
{
ThrowTest();
}
catch
{
}
sw.Stop();
Console.WriteLine("With Exception " + sw.ElapsedTicks);
sw.Restart();
try
{
Return();
}
catch
{
}
sw.Stop();
Console.WriteLine("With Return " + sw.ElapsedTicks);
Console.ReadLine();
}
}
}
這就是你等待的輸出。
我的概念證明非常簡單。在一個函式中,我丟擲了一個異常,在另一個函式中,我在檢查使用者輸入後返回一個布林值。我還附上了一個計算器的螢幕,讓你相信異常處理是如何影響程式碼效能的。
因此,我們可以得出這樣一個結論:“不要為使用者輸入驗證引發異常。”使用布林返回技術(或類似的技術)來驗證業務邏輯中的輸入”。因為異常物件的開銷非常大。
02
—
永遠不要在迴圈中實現try-Catch
是的,它也與異常處理有關。我重複“永遠不要在迴圈中執行try-catch”。讓我用一個例子來證明。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.NetworkInformation;
namespace Test1
{
class Program
{
static void Method1()
{
for (int i = 0; i < 1000; i++)
{
try
{
int value = i * 100;
if (value == -1)
{
throw new Exception();
}
}
catch
{
}
}
}
static void Method2()
{
try
{
for (int i = 0; i < 1000; i++)
{
int value = i * 100;
if (value == -1)
{
throw new Exception();
}
}
}
catch
{
}
}
static void Main(string[] args)
{
Stopwatch sw = new Stopwatch();
sw.Start();
Method1();
sw.Stop();
Console.WriteLine("Within Loop " + sw.ElapsedTicks);
sw.Restart();
Method2();
sw.Stop();
Console.WriteLine("Outside of Loop " + sw.ElapsedTicks);
Console.ReadLine();
}
}
}
這是輸出螢幕。
在method1的這個程式中,我在for迴圈中實現了異常處理機制,而在method2中,我在沒有迴圈的情況下實現了異常處理機制。我們的輸出視窗表明,如果我們在for迴圈外實現try-catch程式的執行速度將比迴圈內的try-catch快2倍。
同樣,唯一的結論是“不要在專案的迴圈中實現try-catch。(是的!不僅在for迴圈中,而且在任何迴圈中。)