Each exception class must be derived from Exception class or from some of its descendant:
type
EMyException = class(Exception);
EMyMathError = class(EMathError);
Exception can be raised by raise reserved word:
function Division(X,Y: Double): Double;
begin
Result:=0;
if Y=0 then raise EMathError.Create('Division by zero')
else Result:=X/Y;
end;
There are two ways to process exceptions: try...except and try...finally. The execution code must be placed between try and except. The exception handler code must be placed between except and end.
try
C:=A div B;
except
ShowMessage('Error!');
end;
You can analyse the exception type in the handler code and use any exception object properties, like HelpContext and Message, inherited from base Exception class:
try
// some code here
except
on E: Exception do
begin
if E is EMathError then ShowMessage('Math error: '+E.Message);
if E is EInOutError then ShowMessage('InOut error: '+E.Message);
end;
end;
By default try...except suppresses the exception and if you want to pass it to the default exception handler, you have to reraise it:
try
// some code here
except
on E.Exception do LogMemo.Lines.Add(E.Message);
raise;
end;
Any unhandled exceptions passed to the Application exception handler. This handler calls OnException event then shows the error message box.
If you want to execute some code independently of exceptions which can occur, just use try...finally construction. Code please into the finally block will be always executed independently from raised exceptions:
ClientList:=TList.Create;
try
// working with ClientList
finally
// try...finally guarantees that this code will be executed,
// so the ClientList object will be always destroyed
ClientList.Free;
end;
Of course, you can combine try...except and try..finally:
ClientList:=TList.Create;
try
try
// working with ClientList
except
// suppress exception and add error message to log
on E.Exception do LogMemo.Lines.Add(E.Message);
end;
finally
// try...finally guarantees that this code will be executed,
// so the ClientList object will be always destroyed
ClientList.Free;
end;
|