Delphi中,若StrToDate()未使用TFormatSettings参数化,直接调用是否应引发AV异常?

更新于
2026-10-05 01:38:59
1阅读来源:SEO问题
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计309个文字,预计阅读时间需要2分钟。

为了使代码更简洁,并避免使用复杂术语,以下是对您提供的代码段进行简化和改写的版本:

只是为了好玩:为什么这段代码给AV而不是抛出异常?procedure TForm1.Button1Click(Sender: TObject);var fs: TFormatSettings;begin strtodate('2011-01-01', fs);end;

这段代码的异常处理被省略了,因为`fs`变量未初始化。正确的做法是在使用它之前初始化`fs`。以下是改进后的代码:

只是为了好玩:为什么这段代码不抛出异常?procedure TForm1.Button1Click(Sender: TObject);var fs: TFormatSettings;begin fs :=TFormatSettings.Create; // 初始化fs try strtodate('2011-01-01', fs); finally fs.Free; // 释放fs end;end;

这样,即使`strtodate`函数调用失败,代码也不会抛出异常,而是会通过`try...finally`块来确保资源被正确管理。

只是为了好奇:为什么这段代码给出AV而不是抛出异常?

procedure TForm1.Button1Click(Sender: TObject); var fs: TFormatSettings; begin strtodate('2011-01-01', fs); end; 您的代码引发异常,因为fs未初始化.

uses SysUtis, Windows; procedure TForm1.Button1Click(Sender: TObject); var fs: TFormatSettings; begin GetLocaleFormatSettings(GetSystemDefaultLCID, fs); // what is your short-date format? strtodate('2011-01-01', fs); end;

本文共计309个文字,预计阅读时间需要2分钟。

为了使代码更简洁,并避免使用复杂术语,以下是对您提供的代码段进行简化和改写的版本:

只是为了好玩:为什么这段代码给AV而不是抛出异常?procedure TForm1.Button1Click(Sender: TObject);var fs: TFormatSettings;begin strtodate('2011-01-01', fs);end;

这段代码的异常处理被省略了,因为`fs`变量未初始化。正确的做法是在使用它之前初始化`fs`。以下是改进后的代码:

只是为了好玩:为什么这段代码不抛出异常?procedure TForm1.Button1Click(Sender: TObject);var fs: TFormatSettings;begin fs :=TFormatSettings.Create; // 初始化fs try strtodate('2011-01-01', fs); finally fs.Free; // 释放fs end;end;

这样,即使`strtodate`函数调用失败,代码也不会抛出异常,而是会通过`try...finally`块来确保资源被正确管理。

只是为了好奇:为什么这段代码给出AV而不是抛出异常?

procedure TForm1.Button1Click(Sender: TObject); var fs: TFormatSettings; begin strtodate('2011-01-01', fs); end; 您的代码引发异常,因为fs未初始化.

uses SysUtis, Windows; procedure TForm1.Button1Click(Sender: TObject); var fs: TFormatSettings; begin GetLocaleFormatSettings(GetSystemDefaultLCID, fs); // what is your short-date format? strtodate('2011-01-01', fs); end;