Throwing Exceptions
Throwing Exceptions
Many programmers mis-use exceptions to signal conditions that are not exceptional.
A subroutine should only throw an exception if the subroutine cannot be expected to deal with the condition. For instance, an API for a multi-tasking operating system that does not provide an atomic check-for-disk-full-and-then-write-to-file function will need to throw an exception if the disk fills during a write. Even if the caller used a check for disk space first this would not help because another process could fill the disk betwen the check and the write.
An analogous situation inside a program might be a buffer of fixed size and a subroutine that adds to the buffer. However, if the buffer is under the control of a single thread there will never be a need to throw an exception if it fills because this is an entirely predictable state of affairs and no other process can alter the state of the buffer between checking for free space and writing to it. In this case it is more logical to check for free space and only write if there is space. Now if the buffer does fill it is a genuinely exceptional circumstance.
Even if the program is multi-tasking we can still write code that doesn't use exceptions to manage the buffer because we can provide functions that reserve space in the buffer or provide atomic check-and-write procedures. The check-and-write procedure would be a critical section or monitor. Of course care must be taken to avoid deadlocks but this is the case anyway and has nothing to do with exceptions.
No comments:
Post a Comment