What happens when the code in the finally block blocks an exception?

I have a simple block of legacy code that is inside a loop that scans some potentially bad xml node on node and needs to be refactored because it doesn't work as intended:

Try
   xmlFrag.LoadXml("<temproot>" & strXMLfragment & "</temproot>")
   writer.WriteRaw(strXMLfragment)
Catch ex As Exception
   InvalidXML = True
End Try

This block is designed to validate xml, and then write xml out. This is actually checking for invalid xml, and then writing the xml out is only if it is valid. Therefore, it must be corrected for the intended purpose.

My first attempt to fix:

Try
   xmlFrag.LoadXml("<temproot>" & strXMLfragment & "</temproot>")
   'writer.WriteRaw(strXMLfragment)
Catch ex As Exception
   InvalidXML = True
Finally
   writer.WriteRaw(strXMLfragment)
End Try

, , WriteRaw . , WriteRaw, , .

, :

Try
   xmlFrag.LoadXml("<temproot>" & strXMLfragment & "</temproot>")
Catch ex As Exception
   InvalidXML = True
End Try
Try
   writer.WriteRaw(strXMLfragment)
Catch
End Try

, . ?

+4
3

:

Try
   writer.WriteRaw(strXMLfragment)
   xmlFrag.LoadXml("<temproot>" & strXMLfragment & "</temproot>")

Catch ex As Exception
   InvalidXML = True
End Try

WriteRaw XML, . LoadXml xml out. , InvalidXML , .

+2

Finally excpetion, : , .

, strXMLfragment - null ( - ).

, / , Try.

+3

To make it cleaner, you can port your first Try / Catch to your own private function and make it reusable:

Private Function TryParseXml(ByVal xml as String) as Boolean
    Try
        XDocument.Parse(xml)
        Return True
    Catch ex As Exception
        Return False
    End Try
End Function

Then wrap your writer.WriteRaw in your own Try / Catch.

Dim myXml = "<temproot>" & strXMLfragment & "</temproot>"
If TryParseXml(myXml) Then
    xmlFrag.LoadXml(myXml)
Else
    Try
        writer.WriteRaw(strXMLfragment)
    Catch ex as Exception
        ' handle exception
    End Try
End If

Yes, the end result is the use of two Try / Catch blocks. There is no real way around this, as the only real way to determine if Xml is valid is to try to parse it and wait for it to explode.

+3
source

Source: https://habr.com/ru/post/1524070/


All Articles