0

I'm fairly new to programming and I'm trying to figure out how I can throw custom exceptions. I'm trying to parse a decimal value off of an XML node and checking if it is less than 0. I want it to throw a message if the value <= 0. In all other cases, I want to throw a default exception message.

Something like this:

Parse the node

If node is nothing or contains nothing,
throw exception ("cant be blank")

else

try 

decimalValue =decimal.parse(node)

If decimalValue < 0

 then throw custom exception message
End If

catch 
  default exception
Emmanuel DURIN
  • 4,803
  • 2
  • 28
  • 53
Sonam Nathani
  • 21
  • 1
  • 2
  • 3
    You should avoid throwing exceptions unless you have a truly exceptional situation - like running out of hard drive space or network dropping out. If you're parsing `decimal` numbers it might be best to pass out a `decimal?` with `null` representing a missing value. – Enigmativity Nov 11 '15 at 01:12
  • Also, you should always avoid doing a "catch default exception". It's bad programming practice. You should only catch specific exceptions that you can deal with. Don't just catch everything as it will hide errors and make your code hard to debug. – Enigmativity Nov 11 '15 at 01:13
  • Exception programming... please don't do that – T.S. Nov 11 '15 at 04:31

1 Answers1

0

Exceptions are useful for propagating signals between application layers without having to modify the return values/protoypes of intermediate methods.

Exceptions are classes, so you can put inside the exception objects all data about exception circumstances.

You can create your custom exception classes.
For instance :

Public Class NegativeValueException : Inherits ApplicationException
  Sub New(_value As Double)
    Value = _value
  End Sub
  Public Property Value() As Double
End Class

Riasing the exceptions :

Throw New NegativeValueException (value)

If you often have to check for negative value, you can write a custom helper function for streamlining :

Shared Sub CheckForPositiveValue(_value As Double)
    If _value < 0 Then
        Throw New NegativeValueException(_value)
    End If
End Sub

Regards

Emmanuel DURIN
  • 4,803
  • 2
  • 28
  • 53
  • FYI, current guidance from MS is that ApplicationException was a bad idea and custom exceptions should inherit from Exception instead: http://stackoverflow.com/questions/52753/should-i-derive-custom-exceptions-from-exception-or-applicationexception-in-net – ThatShawGuy Nov 12 '15 at 16:22