Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>One problem with your question is that you didn't specify the desired semantics. There are two possible interpretations, and which solution is better, depends on that choice. I assume being unable to load the fallback, is a fatal error.</p> <ol> <li>If the first file does exist, load it, else load the second. If the first file exists, but could not be loaded, show an error.</li> <li>If the first file cannot be loaded, fallback to the second.</li> </ol> <p>If you want the semantics of 1) your first code is fine.</p> <p>If you want the semantics of 2), neither is good. The first code doesn't have these semantics because:</p> <ol> <li>It has a race condition. If the image gets deleted between checking the existence of the file and loading it, it'll fail.</li> <li>If the file exists, but cannot be loaded, an exception will be thrown. This can happen if the file is no valid image, or cannot be opened.</li> </ol> <p>The second one uses exceptions for a common case, which is bad.</p> <p>So to achieve the second semantics I'd use:</p> <pre><code>procedure LoadImage(img: TImage; filename: string); var success:boolean; begin success := false; if FileExists(filename) then try img.Picture.LoadFromFile(filename); success := true; except end if not success then img.Picture.LoadFromFile('default.jpg'); end; </code></pre> <p>Checking for existence before opening makes the error case faster, but the success case slower. So which one is faster depends on your usage.</p> <p>Personally I'd use the third variant over the second, even if the image is only missing occasionally, since I believe a normally operating application should not throw exceptions. I'd only care about the performance issue if benchmarking revealed it to be noticeable.</p> <p>You should also consider a more targeted exception clause. Blanket catching all exception is bad style. Unfortunately I couldn't find a clear specification which exceptions are thrown by <code>TPicture.LoadFromFile</code>, so I'll leave in the blanket clause for now.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload