Pages

Monday, January 9, 2012

How to handle exception in delphi

Almost in all programming language, there are mechanism to handle exception. So do in delphi. We can use try...except mechanism. The following is the example of exception handling in delphi :
var
  bagi, nol : Integer;
begin 
  try
    nol   := 0;
    bagi := 1 div zero;
    ShowMessage('1/0 = ' + IntToStr(bagi));
  except
    on E : Exception do
      ShowMessage(E.ClassName + ' error raised, with message : ' + E.Message);
  end;
end;
In that example, if the try clause generates an exception, it will the execute except clause that will display window showing what type of error generated. This is used to take alternative action when something unexpected goes wrong. Beside that, the other form of handle exception can be done as follow :
var
  bagi, nol : Integer;
begin 
  try
    nol   := 0;
    bagi := 1 div zero;
    ShowMessage('1/0 = ' + IntToStr(bagi));
  finally
    if bagi = -1 then
    begin
      ShowMessage('Number was not assigned a value - using default');
      bagi := 0;
    end;
  end;
end;
In a try...finally construct, the finally statement will be executed absolutely whether thereis error or not. It is normally used to allow cleanup processing, such as freeing memory etc. Both kind of construct cannot be combined together using try..except..finally. So, the question is how to handle exception while we want to execute a set of clean up statements, in other words, how to tricky combine both except and finally ?? This can be done with nested try statements, as construct below :
Try
  Try
    ...
  Except
    ...
  End;
Finally
  ...
End;
Need to be noticed that when you want to test exception handling, don't do it using F9/Run. But do it by execute application (ctrl+f9 then double click application.exe created)

No comments:

Post a Comment

Don't Forget To Join Our Community
×
Widget