Originale-mail to me for new edition

 

When to use exceptions

 

Exceptions provide an elegant way to trap runtime errors without halting the program and without awkward conditional statements. The complexity of Object Pascal’s exception-handling mechanism, however, makes it inefficient, and it should therefore be used judiciously. While it is possible to raise exceptions for almost any reason, and to protect almost any block of code by wrapping it in a try...except or try...finally statement, in practice these tools are best reserved for special situations.

Exception handling is appropriate for errors whose chances of occurring are low or difficult to assess, but whose consequences are likely to be catastrophic (such as crashing the application); for error conditions that are complicated or difficult to test for in if...then statements; and when you need to respond to exceptions raised by the operating system or by routines whose source code you don’t control. Exceptions are commonly used for hardware, memory, I/O, and operating-system errors.

Conditional statements are often the best way to test for errors. For example, suppose you want to make sure that a file exists before trying to open it. You could do it this way:

try

  AssignFile(F, FileName);

  Reset(F);  // raises an EInOutError exception if file is not found

except

  on Exception do ...

end;

But you could also avoid the overhead of exception handling by using

if FileExists(FileName) then  // returns False if file is not found; raises no exception

begin

  AssignFile(F, FileName);

  Reset(F);

end;

Assertions provide another way of testing a Boolean condition anywhere in your source code. When an Assert statement fails, the program either halts or (if it uses the SysUtils unit) raises an EAssertionFailed exception. Assertions should be used only to test for conditions that you do not expect to occur. For more information, see the online Help for the standard procedure Assert.

 

Topic groups

 

See also

Assert procedure

Exceptions: Overview

 

 

译文

 

何时使用异常

 

异常为捕获错误时既不停止程序执行也不使用复杂笨拙的条件语句提供了一流的途径。Object Pascal的异常处理机制相当复杂,在一定程度上降低了程序执行效率,所以,应当慎重使用异常。在try...excepttry...finally语句中,任何原因引发的异常在任何代码快中几乎都可以被包装,而在实践中这些工具最好保留用于特殊的情况(从而尽可能避免降低程序效率)。

异常处理适合这些情况:错误发生的几率较低或者很难访问,但它们的结果很可能是灾难性的(如彻底终止应用程序);错误发生的条件较复杂或难以用if...then语句测试到;需要对操作系统或源代码不受开发者控制的例程等引发的异常响应时。异常一般用于硬件、内存、输入/输出(I/O)以及操作系统错误。

条件语句通常是测试错误的最佳手段。例如,假定在试图打开一个文件之前要确信其存在,可以如下实现:

try

  AssignFile(F, FileName);

  Reset(F);  //假如文件不存在,那么引发一个 EInOutError 异常

except

  on Exception do ...

end;

但也可以通过下面的方法避免上面的异常处理:

if FileExists(FileName) then  //如果文件不存在,那么返回False;这不会引发任何异常

begin

  AssignFile(F, FileName);

  Reset(F);

end;

断言机制(Assertions)提供了测试布尔条件的另一个手段,它可以用于源代码的任何位置。当一条断言(Assert)语句失败时,程序既不会终止(如果程序使用了SysUtils单元),也不会引发EAssertionFailed异常。断言机制应当用于测试不希望发生的条件。更多信息见联机帮助中的标准过程Assert

 

主题组

 

相关主题

Assert过程(详细信息见联机帮助)

异常:概述