我有點沮喪,試圖找出最好的路線是用try-catch語句處理C#中的異常。我想擁有代碼,所以如果試圖打開一個註冊表項引發異常,那麼它會移動到下一個註冊表項。我能想到的唯一方法就是通過將每個函數調用封裝在try-catch語句中,但對我來說,這似乎有很長的路要走。更少的try-catch語句?
- 有沒有其他方法可以做到這一點?
- 你可以擁有單個try-catch語句中的所有代碼,並且當發生異常時,是否將它移動到下一行代碼中(如step over)?
- 我知道這可能是一個否,但如果變量設置在參數中,可以使用
ScanSubKey
函數檢查異常嗎?
沒有的try-catch語句
ScanSubKey(Registry.ClassesRoot);
ScanSubKey(Registry.LocalMachine.OpenSubKey("SOFTWARE"));
ScanSubKey(Registry.CurrentUser.OpenSubKey("SOFTWARE"));
if (Is64BitOS)
{
ScanSubKey(Registry.ClassesRoot.OpenSubKey("Wow6432Node"));
ScanSubKey(Registry.LocalMachine.OpenSubKey("SOFTWARE\\Wow6432Node"));
ScanSubKey(Registry.CurrentUser.OpenSubKey("SOFTWARE\\Wow6432Node"));
}
例
try {
ScanSubKey(Registry.ClassesRoot);
}
catch (Exception ex) {
Debug.WriteLine("The following error occurred opening a registry key: " + ex.Message);
}
try {
ScanSubKey(Registry.LocalMachine.OpenSubKey("SOFTWARE"));
}
catch (Exception ex) {
Debug.WriteLine("The following error occurred opening a registry key: " + ex.Message);
}
try {
ScanSubKey(Registry.CurrentUser.OpenSubKey("SOFTWARE"));
}
catch (Exception ex) {
Debug.WriteLine("The following error occurred opening a registry key: " + ex.Message);
}
if (Is64BitOS)
{
try {
ScanSubKey(Registry.ClassesRoot.OpenSubKey("Wow6432Node"));
}
catch (Exception ex) {
Debug.WriteLine("The following error occurred opening a registry key: " + ex.Message);
}
try {
ScanSubKey(Registry.LocalMachine.OpenSubKey("SOFTWARE\\Wow6432Node"));
}
catch (Exception ex) {
Debug.WriteLine("The following error occurred opening a registry key: " + ex.Message);
}
try {
ScanSubKey(Registry.CurrentUser.OpenSubKey("SOFTWARE\\Wow6432Node"));
}
catch (Exception ex) {
Debug.WriteLine("The following error occurred opening a registry key: " + ex.Message);
}
}
AFAIK這是不可能的,請參閱[這裏](http://social.msdn.microsoft.com/Forums/en-US/2294d2ce-e6ae-4152-b022-61aa2ae9372d/trycatchcontinue-with-next-line-在嘗試塊?forum = Vsexpressvcs) – AlphaDelta