Say I have a list of objects of the same type. I want to iterate over this list of objects and execute a “dangerous” method for each of them. If an exception occurs in this method, is it a bad practice for the method to catch the exception and set the error property for the object?
Here is a brief example where the Start () Car method catches its own exception and stores it in the Problem property:
Sub Main()
Dim ford As New Car("ford", "1988")
Dim chevy As New Car("chevy", "1992")
Dim honda As New Car("honda", "2002")
Dim carList As New List(Of Car)
carList.Add(ford)
carList.Add(chevy)
carList.Add(honda)
For Each c As Car In carList
c.Start()
Next
Dim cr As New CarReport
cr.ReportProblems(carList)
End Sub
A 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
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
: , (.. Sub Main() ) Problem Car? . , , - Car, .
: - , , .