Originally Posted by
Elysia
Think of it this way:
You have an operation, such as copying and replacing a file.
To ensure all goes well, you break it into parts:
- You open the source file.
- You open the (temporary) destination file.
- You read a chunk from the source file.
- You read the chunk to the destination file (and repeat until done).
- You then rename the destination file you're replacing.
- You then rename the temporary destination file to the name of the file you're replacing.
- You then delete the renamed original file you were supposed to replace.
But what if an error occurs somewhere in this chain?
Perhaps you don't have permission to open or write the source or destination file. Perhaps there a read error or write error when reading/writing to the files.
In this case, you might have to abort because you a subsequent task cannot execute until all of its previous tasks have been completing.
This is where exceptions come in. Say a task fails. That task then throws an exception. This exception is then caught and an error reported.
To be technical, the try block would surround all of these tasks, and the catch block would follow just after the try block.