VB.NET尝试/捕获块问题-为什么不引发异常

时间:2019-08-01 10:58:07

标签: vb.net exception visual-studio-2017 call comexception

您好,我的情况是我的“尝试/捕获”块的行为不符合预期。在这种情况下,通过调用Excel函数会生成ComException。该代码位于Try / Catch块内,并且捕获了异常,但是该代码暂停,而不是按预期在整个调用堆栈中“冒泡”,由调用过程处理。下面列出了代码以及调用堆栈中的相关内容。

    Public Overrides Sub CleanDataSet()
        Const procName As String = "CleanDataSet"


        Try
            _previousState = ""
            _previousPlant = ""

            _firstSourceDataRow = 5
            _currentWorkSheet = _mySourceWorkSheet
            _currentRegion = _currentWorkSheet.UsedRange

            _lastSourceDataRow = _currentRegion.Rows.Count + _firstSourceDataRow - 2

            _myWorkbook = _myXLApp.ActiveWorkbook

            'Add a new worksheet to the workbook and call it AlarmAnalysis
            _currentWorkSheet = _myWorkbook.Worksheets.Add()
            _mySheetName = "AlarmAnalysis" & _nextKpiSheetNo
            _currentWorkSheet.Name = _mySheetName

            'Now copy the source data into the RTUAvailability worksheet
            _currentWorkSheet = _mySourceWorkSheet
            Dim regionToCopy As String
            regionToCopy = _currentRegion.Address.ToString
            _currentWorkSheet.Range(regionToCopy).Copy()

            _currentWorkSheet = _myWorkbook.Worksheets(_mySheetName)
            _currentWorkSheet.Paste()

            'Insert an additional title row
            _currentWorkSheet.Rows(3).Resize(1).Insert()

            _logger.SendLog(_typeName & "." & procName & " - Deleting unrequired columns from the KPI data.", NLog.LogLevel.Trace)

            'Now delete the unrequired columns
            DeleteColumns(_currentWorkSheet, _currentRegion, _timeField & ", ALARM NAME, STATUS, SUBSTATION NAME, COMMS ROUTE, KPI ALARM, KPI STATUS", _titleRow)

            'Build the report titles
            _currentWorkSheet.Columns.AutoFit()
            _currentWorkSheet.Range(_timeCol & _firstSourceDataRow).Select()
            _currentRegion = _currentWorkSheet.Range(_timeCol & _titleRow).CurrentRegion

            _firstRow = _currentRegion.Row + 1
            _lastRow = _currentRegion.Rows.Count + _firstRow - 2

            _currentWorkSheet.Range(_eventTypeCol & _firstRow - 1).Value = "EVENT TYPE"
            _currentWorkSheet.Range(_eventTypeCol & _firstRow - 1).AddComment("Widow" & vbCrLf & _
                                                                    "Orphan" & vbCrLf & _
                                                                    "Paired" & vbCrLf & _
                                                                    "Derived")


            _currentWorkSheet.Range(_durationCol & _firstRow - 1).Value = _totalColName
            _currentWorkSheet.Columns.AutoFit()

            _currentWorkSheet.Range(_currentWorkSheet.Cells(_firstRow - 1, 1), _currentWorkSheet.Cells(_firstRow - 1, GetColNo(_currentWorkSheet, _firstRow - 1, _totalColName))).Font.Bold = True

            'Now sort the data according to the unique key
            _currentWorkSheet.Range(_timeCol & _firstRow - 1 & ":" & "D" & _lastRow).Select()
            _currentWorkSheet.Range("C5").Sort(Key1:=_currentWorkSheet.Range("C5"), _
                Order1:=Excel.XlSortOrder.xlAscending, Key2:=_currentWorkSheet.Range("A5"), _
                Order2:=Excel.XlSortOrder.xlAscending, Header:=Excel.XlYesNoGuess.xlYes, OrderCustom:=1, _
                MatchCase:=False, Orientation:=Excel.XlSortOrientation.xlSortColumns)

            'Set some variables for manipulating the data
            _eventTimeColNo = GetColNo(_currentWorkSheet, _firstRow - 1, _timeField)
            _eventTypeColNo = GetColNo(_currentWorkSheet, _firstRow - 1, "EVENT TYPE")
            _plantColNo = GetColNo(_currentWorkSheet, _firstRow - 1, "SUBSTATION NAME")
            _commsRouteNo = GetColNo(_currentWorkSheet, _firstRow - 1, "COMMS ROUTE")
            _originalStatusColNo = GetColNo(_currentWorkSheet, _firstRow - 1, "STATUS")
            _statusColNo = GetColNo(_currentWorkSheet, _firstRow - 1, "KPI STATUS")
            _durationColNo = GetColNo(_currentWorkSheet, _firstRow - 1, _totalColName)

            'Code to iterate through the the rows of data and pair events
            Iterate()

            'Set the variable content in the sheet
            GenerateVariablesSheet(_myWorkbook, _nextKpiSheetNo, _numTimeIntervals)

            'Generate the Widow and Orphans Page
            GenerateWidowsAndOrphansSheet()

            'Now build the pivot tables
            _currentWorkSheet.Activate()

            'If we have valid data to process
            If _currentWorkSheet.Range(_timeCol & _firstRow).Value IsNot Nothing Then
                Me.ValidData = True
                BuildTables(_myWorkbook, _currentWorkSheet, _firstRow - 1, _lastRow, 1, _durationColNo, _durationColNo + 2, "SUBSTATION NAME", _totalColName, _totalColName)
            Else
                Me.ValidData = False
                'Enter the 'No Valid Data' banner in the report'
                Dim banRng As Excel.Range
                banRng = _currentWorkSheet.Range(_timeCol & _firstRow)
                MarkWithBanner(_currentWorkSheet, "NO VALID DATA - View the Widows and Orphans Worksheet", banRng, 24, Color.Red)
                _logger.SendLog(_typeName & "." & procName & " - No valid data to process", NLog.LogLevel.Trace)
            End If

            _currentWorkSheet.Calculate()
            _currentWorkSheet.Columns.AutoFit()

        Catch ex As Exception
            Throw **'CODE HALTS HERE INSTEAD OF EXCEPTION BEING THROWN'**
        Finally

        End Try
    End Sub

这是生成的异常:

at Microsoft.VisualBasic.CompilerServices.LateBinding.InternalLateCall 
(Object o, Type objType, String name, Object[] args, String[] paramnames, Boolean[] CopyBack, Boolean IgnoreReturn)
at Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateCall(Object  
Instance, Type Type, String MemberName, Object[] Arguments, String[]  ArgumentNames, Type[] TypeArguments, Boolean[] CopyBack, Boolean IgnoreReturn)
at Accipiter.PSALERTS2018.Common.NCPCommsAnalysisReport.BuildTables(Workbook 
wBook, Worksheet wSheet, Int64 titleRow, Int64 lastRow, Int64 dataStartCol, 
Int64 dataEndcol, Int64 ptColPos, String plantID, String pivotField, String 
totalColName) 
in C:\Users\TE602510\Documents\_VSSWorkArea\PSALERTS 2018\PSALERTS 
Client\Common\KPIReporting.vb:line 3758

这是调用堆栈:

Common.dll!Accipiter.PSALERTS2018.Common.NCPCommsAnalysisReport.CleanDataSet() Line 4078    Basic
[Native to Managed Transition]  
[Managed to Native Transition]  
Microsoft.VisualBasic.dll!Microsoft.VisualBasic.CompilerServices.Symbols.Container.InvokeMethod(Microsoft.VisualBasic.CompilerServices.Symbols.Method TargetProcedure, object[] Arguments, 
    bool[] CopyBack, System.Reflection.BindingFlags Flags)  Unknown
Microsoft.VisualBasic.dll!Microsoft.VisualBasic.CompilerServices.NewLateBinding.CallMethod(Microsoft.VisualBasic.CompilerServices.Symbols.Container BaseReference, string MethodName, 
    object[] Arguments, string[] ArgumentNames, System.Type[] TypeArguments, bool[] CopyBack, System.Reflection.BindingFlags InvocationFlags, bool ReportErrors, 
    ref Microsoft.VisualBasic.CompilerServices.OverloadResolution.ResolutionFailure Failure)    Unknown
Query.exe!QueryMain.BuildReport(Object dataArray) Line 6069 Basic
Query.exe!QueryMain.uxBWFetch_DoWork(Object sender, System.ComponentModel.DoWorkEventArgs e) Line 809   Basic
System.dll!System.ComponentModel.BackgroundWorker.OnDoWork(System.ComponentModel.DoWorkEventArgs e) Unknown
System.dll!System.ComponentModel.BackgroundWorker.WorkerThreadStart(object argument)    Unknown
[Native to Managed Transition]  
[Managed to Native Transition]  
mscorlib.dll!System.Runtime.Remoting.Messaging.StackBuilderSink.AsyncProcessMessage(System.Runtime.Remoting.Messaging.IMessage msg, System.Runtime.Remoting.Messaging.IMessageSink replySink)   Unknown
mscorlib.dll!System.Runtime.Remoting.Proxies.AgileAsyncWorkerItem.ThreadPoolCallBack(object o)  Unknown
mscorlib.dll!System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(object state)  Unknown
mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx)   Unknown
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx)   Unknown
mscorlib.dll!System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()  Unknown
mscorlib.dll!System.Threading.ThreadPoolWorkQueue.Dispatch()    Unknown
mscorlib.dll!System.Threading._ThreadPoolWaitCallback.PerformWaitCallback() Unknown

0 个答案:

没有答案