Kinds of Errors
This lesson sheds light on different types of errors and explains how exceptions can be used to handle different types of errors.
We'll cover the following
Kinds of errors #
We have seen how useful the exception mechanism is. It enables both the lower and higher-level operations to be aborted right away instead of letting the program continue with incorrect or missing data or behave in any other incorrect way. This does not mean that every error condition warrants throwing an exception. There may be better things to do depending on the kinds of errors.
User errors #
Some errors are caused by the user. As we have seen above, the user may have entered a string like “hello” even though the program has been expecting a number. It may be more appropriate to display an error message and ask the user to enter appropriate data again.
Even so, it may be fine to accept and use the data directly without validating the data upfront; as long as the code that uses the data would throw anyway. However, it is important to be able to notify the user of why the data is not suitable.
For example, let’s look at a program that takes a file name from the user. There are at least two ways of dealing with potentially invalid file names:
-
Validating the data before use: We can determine whether the file with the given name exists by calling
exists()
of thestd.file
module:if (exists(fileName)) { // yes, the file exists } else { // no, the file doesn't exist }
This gives us the chance to be able to open the data only if it exists. Unfortunately, it is still possible that the file cannot be opened even if
exists()
returns true if, for example, another process in the system deletes or renames the file before this program actually opens it.
For that reason, the following method may be more useful. -
Using the data without first validating it: We can assume that the data is valid and start using it right away because
File
would throw an exception if the file cannot be opened anyway.
Get hands-on with 1400+ tech skills courses.