Question

I have a class that I am writing that is basically going to be used to send transactions to a credit card processor.

As a safeguard I do a few checks to validate the properties being passed in to the functions and my question is if I detect something wrong, say a blank or invalid credit card number, should I raise a custom event and force whatever is calling the function to handle the custom event in order to handle the exception or should I throw a new exception and just assume that whatever calls my class will have its own try's and catches in place to handle the exception?

I'm curious which is more efficient but more concerned with accepted standards in regards to manually using the throw keyword.

Was it helpful?

Solution

There is no way to force a caller to register the event thus if you are handling this through events, there is a chance that the consumer will ignore the issue. If it should be a blocking issue, use an exception.

From an efficiency perspective, there is an overhead to throwing (more specifically catching) exceptions, but if you're in a situation where nothing can happen it is truly an exception case. Also, consider including a Trace.Assert to assist debugging during development.

OTHER TIPS

Your best bet is to raise an exception. This will force the program to have to deal with the issue explicitly rather than relying on the developer to register a handler.

Exceptions also mean that you can handle the error closer to the code that can deal with it. For example, your transaction processor may be buried deep down in the call stack, but it's actually your GUI layer than can deal with the error by showing a message. With the event approach you wouldn't be able to attach your gui to the transaction processor as it wouldn't have access to it, but with the exception approach you can handle its errors.

If the validation fails this is not an "event".

I would recommend that you do the following:

1 - Add a method with a boolean return called something like ValidateDetails

2 - Throw an exception if the validation fails when you try to process the information (you can use the ValidateDetails method yourself to check this)

This would allow the developer to perform their own check that they have supplied the correct information before sending it for processing and receiving an exception.

Public Class CreditCardProcessor
    Public Function ValidateDetails As Boolean
        'check everything validates here and return True/False accoringly
    End Function

    Public Sub ProcessDetails
        If Not ValidateDetails Then
            Throw New Exception("Validation failed")
            Exit sub
        End If
        'Process the credit card here
    End Sub
End Class
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top