2012-11-13 167 views
1

我寫在C#中的Kinect的應用程序,我有這樣的代碼如何忽略異常

try    //start of kinect code 
{ 
    _nui = new Runtime(); 
    _nui.Initialize(RuntimeOptions.UseSkeletalTracking | RuntimeOptions.UseDepthAndPlayerIndex | RuntimeOptions.UseColor); 

    // hook up our events for video 
    _nui.DepthFrameReady += _nui_DepthFrameReady; 
    _nui.VideoFrameReady += _nui_VideoFrameReady; 

    // hook up our events for skeleton 
    _nui.SkeletonFrameReady += new EventHandler<SkeletonFrameReadyEventArgs>(_nui_SkeletonFrameReady); 

    // open the video stream at the proper resolution 
    _nui.DepthStream.Open(ImageStreamType.Depth, 2, ImageResolution.Resolution320x240, ImageType.DepthAndPlayerIndex); 
    _nui.VideoStream.Open(ImageStreamType.Video, 2, ImageResolution.Resolution640x480, ImageType.Color); 

    // parameters used to smooth the skeleton data 
    _nui.SkeletonEngine.TransformSmooth = true; 
    TransformSmoothParameters parameters = new TransformSmoothParameters(); 
    parameters.Smoothing = 0.8f; 
    parameters.Correction = 0.2f; 
    parameters.Prediction = 0.2f; 
    parameters.JitterRadius = 0.07f; 
    parameters.MaxDeviationRadius = 0.4f; 
    _nui.SkeletonEngine.SmoothParameters = parameters; 

    //set camera angle 
    _nui.NuiCamera.ElevationAngle = 17; 
} 
catch (System.Runtime.InteropServices.COMException) 
{ 
    MessageBox.Show("Could not initialize Kinect device.\nExiting application."); 
    _nui = null; 

} 

我正在尋找一種方式,我的應用程序不會崩潰(異常被忽略不計)時,Kinect的是未連接。我又創建了另外一個問題here,但是這個解決方案並不適用於我的場合,因爲我被迫使用過時的sdk,沒有人可以解決這個問題,所以我嘗試使用不同的方法。我怎樣才能忽略這個異常?如果你想忽略所有的異常(我可以扭轉作出_nui自己以後的變化)

+0

什麼異常被拋出要忽略?一目瞭然,上面的代碼看起來應該忽略在該代碼塊中拋出的任何'COMException',但沒有什麼可以說如果在其他地方訪問_nui時,可能不會拋出空引用異常。 – Chris

+0

這實際上取決於例外情況。您只能「忽略」對您的代碼邏輯不重要的異常。 –

+0

整個_nui點AFTER這部分代碼可以由我來處理(我已經想過了)如何重點是我需要我的應用程序來通過這部分代碼,無論我把什麼放在應用程序的catch括號中在崩潰(拋出異常)在那裏 –

回答

1

當前您正在捕獲所有的ComExceptions。如果您想要捕獲其他異常,則需要爲每個異常提供特定類型。如果你希望你的代碼來捕獲後執行不管是什麼

catch (System.Runtime.InteropServices.COMException) 
    { 
     MessageBox.Show("Could not initialize Kinect device.\nExiting application."); 
     _nui = null; 

    } catch (Exception ex) //this will catch generic exceptions. 
    { 

    } 

您可以將catch塊後,像這樣添加的異常類型。你也可以嘗試使用finally

這樣

try 
{ 
    //logic 
} 
finally 
{ 
    //logic. This will be executed and then the exception will be catched 
} 
+0

不工作,我不知道爲什麼。這是一個System.Windows.Markup.XamlParseException 有沒有辦法找出到底拋出異常的位置?也許這發生在別的地方比這個代碼。我怎樣才能找到? –

+0

@macrian,以及你可以看看你的堆棧跟蹤,看看它在哪裏拋出,或嘗試在Visual Studio中調試 – RAS

+0

我試過了,但我似乎並沒有明白它....我道歉如果我太多了noob –

0

try 
{ 
// your code... 
} 
catch (Exception E) 
{ 
// whatever you need to do... 
}; 

以上是一個包羅萬象的(雖然有些例外,不能被捕獲像#2) 。

REMARK

你就不應該使用上述...你應該找出什麼樣的異常被拋出,趕上的!

+0

不起作用,我不知道爲什麼。這是一個System.Windows.Markup.XamlParseException 有沒有辦法找出到底拋出異常的位置?也許這發生在別的地方比這個代碼。我怎樣才能找到? –

+1

@macrian你可以告訴visual studio調試器在拋出異常時中斷;這可以使某些異常拋出異步操作更容易處理。當然,這可能無助於你的這種特殊情況。查看「Debug」菜單下的「Exceptions ...」選項。 – Rook