My understanding is it is better practice to test beforehand to avoid exceptions, rather than catching them. Is there any way to check if an asset file exists before attempting to open it?
My understanding is it is better practice to test beforehand to avoid exceptions, rather
Share
There is no such feature available to assets, however, there is no need for it (see below).
This is only true if an exception is a part of the normal (expected) operation of your application. In other words, if an exception is a statistically common event (e.g. you expect it to happen “often” at a certain place), then catching it may have significant performance costs. (In practice, this matters only in case of many exceptions caught in a short period of time, so benchmarking is always important.)
Since you usually don’t expect an asset to be missing when trying to access it (otherwise something is wrongly designed in your application), it is fine to use an exception handler for exceptional cases.
To sum up, error handling with exceptions has performance costs, but errors (especially errors to be suppressed) are expected to be rare events. If you expect errors to happen very often in a certain part of your application, then something may be wrong in your design. (Some very exceptional situations are possible where this is not true, but these are very rare and atypical application domains.)
In practice: in your case, e.g. it is OK to use exceptions if the asset name comes from external (e.g. user) input. This is because the “frequency” of possible exceptions is low. On the other hand, if you are trying to decide for many assets if each of them exists (e.g. in a loop), then exception handling might have unacceptable performance costs — but I can hardly imagine that such a thing would be needed.