Jes*_*own 3 delphi exception-handling
高代表用户对我今天早些时候提出的另一个问题的评论表明,更换try/finally和try/except的顺序会更好.
所以,而不是这个:
try
try
//some code
//something that throws an exception, eg: EIndexOutOfRangeException
//more code
except on E : EIndexOutOfRangeException do begin .... end;
finally
// some cleanup code
end;
Run Code Online (Sandbox Code Playgroud)
它会有try/finally嵌套在里面,而try/except在外面:
try
try
//some code
//something that throws an exception, eg: EIndexOutOfRangeException
//more code
finally
// some cleanup code
end;
except on E : EIndexOutOfRangeException do begin .... end;
end;
Run Code Online (Sandbox Code Playgroud)
我想知道什么时候使用这个成语是合适的,也是个好主意,是否有特殊情况你不应该这样做?为什么选择一个而不是另一个?我认为清理代码中抛出的异常将是主要的考虑因素,因为我认为它可以抑制其中一个例外,如果最终抛出异常,但可以防止意外冒泡错误?
您可以同时使用try,catch和finally的编写方式,因情况而异.
考虑下面的代码清单try ...除了在try ... finally之外.
//You will receive a DataSet is some state.
try
try
//Here you'll change its state and perform operations on it.
//If some exception occurred you will handle it.
except
//Handle exception.
end;
finally
//Put the DataSet again in the same state.
end;
Run Code Online (Sandbox Code Playgroud)
上面的代码清单显示了try ...的用法,除了在try ... finally块之外.
考虑以下代码清单,尝试尝试...最后在try ...中除外.
try
LObject:= TObject.Create;
//Create an Object. It better idea to create an object outside try..finally block.
//If some exception occured while creating an object an exception will be thrown.
//However its not a good idea to catch such an exception.Let the system handle it.
try
//Use the Object.
finally
//Free Object.
end;
// Returns True
except
// Returns False.
end;
Run Code Online (Sandbox Code Playgroud)
这里,上述代码清单可以用于这样的情况,其中函数仅返回true和false.如果发生了一些异常,则只需将该值设置为false.