Hi, I have one ShellTreeView, one ShellListView and a splitter on my form. I want to prevent my program raising exception and exiting. How can I check if a path is valid and continue without error? Here's my code so far:
procedure TForm1.ShellTreeView1SelectionChanged(Sender: TObject);
begin
ShowMessage('Changing item');
if (not Assigned(ShellTreeView1.Selected)) then
begin
ShowMessage('Error');
Halt(1);
if (not Assigned(ShellTreeView1.Selected.Items[0])) then
begin
ShowMessage('Error');
Halt(1);
end;
end;
end;
Where is it raising the exception? Surely not in that code if it's not executed!
Anyway, by the time OnSelectionChanged is shot the ShellTreeView is
already populated from the file system, so the selected item must exist or it wouldn't be there. But if you want to make sure you can simply test ShellTreeView.SelectionCount.
Also note that in your code:
if (not Assigned(ShellTreeView1.Selected.Items[0])) then ...
is only executed after you have already determined that ShellTreeView1.Selected is Nil, which makes little sense ... and
will raise an exception
Try this instead:
procedure TForm1.ShellTreeView1SelectionChanged(Sender: TObject);
begin
ShowMessage('Changing item');
if ShellTreeView.SelectionCount < 1 then begin
ShowMessage('Error: SelectionChanged called but no item selected!!!');
//Halt(1); { Unless you're absolutely sure of what you're doing, never use Halt on a GUI app}
Application.Terminate(1);
end else
if ShellTreeView1.Selected.Count < 1 then begin
ShowMessage('Error: Some item selected but Selected.Items[0] = nil');
Application.Terminate(2);
end;
end;
I don't understand well what you're trying to do through that, though, because when you get down to a leaf directory (one which has no directories under it) Selected.Count will be zero (or Selectec.Items[0] will be Nil), as it should, and one can't count that as an error.
I guess that your code is just a test and you intend to do some other thing in that handler?
ETA: To get better help it would be best if you share your program (or a significant portion of it) so that we can see where it's failing.
BTW, when you say: "if statements aren't executed when I run my program", do yo mean the "Changing" mesage appears but the ifs are not executed? If so, that's ... very difficult to understand.