Let's say I have a list of objects of the same type. I want to iterate over that list of objects and execute a "dangerous" method on each of them. If an exception occurs in that method, is it bad practice to have the method itself catch the exception and set an error property on the object?
Here's a quick example where the Start() method of the Car catches its own exception and stores it in its "Problem" property:
Sub Main()
// Build cars.
Dim ford As New Car("ford", "1988")
Dim chevy As New Car("chevy", "1992")
Dim honda As New Car("honda", "2002")
// Create a list of cars.
Dim carList As New List(Of Car)
carList.Add(ford)
carList.Add(chevy)
carList.Add(honda)
// Start all of the cars.
For Each c As Car In carList
// I don't want to stop processing if an exception occurs.
// And I don't care to report any errors now.
c.Start()
Next
// other stuff...
// Now report errors.
Dim cr As New CarReport
cr.ReportProblems(carList)
End Sub
The class that reports any problems:
Public Class CarReport
Public Sub ReportProblems(ByVal c As List(Of Car))
// Report any problems.
For Each c In carList
If Not String.IsNullOrEmpty(c.Problem) Then
Console.WriteLine(c.Problem)
End If
Next
End Sub
End Class
The simple Car class:
Public Class Car
Private _make As String
Private _year As String
Private _problem As String = String.Empty
Public Sub New(ByVal make As String, ByVal year As String)
_make = make
_year = year
End Sub
Public Sub Start()
Try
// Do something that could throw an exception.
Catch ex As Exception
_problem = "Car would not start."
End Try
End Sub
Public ReadOnly Property Problem() As String
Get
Return _problem
End Get
End Property
End Class
EDIT: What if the caller (i.e., Sub Main()
above) caught the exception and then set the Problem property on the Car object? That seems cleaner. What I really need to accomplish is to keep the error text with the particular Car object so it can be passed along to another system for reporting.
Note: The car scenario is a trivial example to illustrate a scenario, I didn't put much thought into the class design.