I want to know if the exception is a "memoryoverflow exception" for example. But if the language on the Operating system is not English but Chinese for example or German, the message changes. And I cannot look the the message string anymore. On MSDN I have not found a exception number to work with. How to find a exception number?
Public Shared Sub Main()
Dim x As Integer = 0
Try
Dim y As Integer = 100 / x
Catch e As Exception'here, 123 is not working
if e is ArithmeticException(123) then Console.WriteLine("Generic Exception Handler: {0}", e.ToString())
End Try
End Sub
Example (look at the <-- line)
Try
m_DxFilGraphManager.Run()
Catch ex As System.Runtime.InteropServices.COMException
If ex.Message.Contains("0x800705AA") Then '<-- Bad methode. How to do it better?
Return "#ERROR: Can not start capturing. It seems to be a possiblity to change the IEEE 1394 bus host controler system driver in your device manager to 'legacy / alt'. " & ex.Message
Else
Return "#ERROR: " & ex.Message
End If
End Try
Use proper exception handling:
Public Shared Sub Main()
Dim x As Integer = 0
Try
Dim y As Integer = 100 / x
Catch e As ArithmeticException
// handle ArithmeticException
Catch e As Exception
// handle Exception
End Try
End Sub
Catching Exception
is bad practice - I suggest reading the documentation.
There are several specific exception types you can use - DivideByZeroException
, NotFiniteNumberException
derive from ArithmeticException
.
Generally in .NET (although that is not enforced by anything but convention), there is a dedicated Exception-type derived from System.Exception
for each cause. So, for example, your "memory overflow" would most likely be signaled by System.OutOfMemoryException
. Checkout the System.Exception class hierarchy on MSDN for more information about the exception types in the .NET framework. Although your code and 3rd party components can always define their own.
Having that said, their are certainly hairy cases, like for example with IOException
. Sometimes you almost don't get around trying to parse error messages - which may be localized of course. Most of the times you can get around this issues.
As a rule, make sure you catch only the exception type you are actually interested in. Also, you may want to limit to number of statements in your try-block to be (rather) sure you are reacting on an exception raised by correct statement.
Finally, too coarse grained exception handling is equally bad as too fine grained exception handling. It always depends on your actual code.
User contributions licensed under CC BY-SA 3.0