In: Computer Science
What does it mean to throw an Exception? Give two examples of when it might be appropriate to throw an Exception.
The term exception is shorthand for the phrase "exceptional event."
An exception is an event, which occurs in the execution cycle of the progra. It disrupts the normal flow of the program's instructions.When an error occurs within a method, the method creates an object and passes it to the runtime system. The object, called and exception object. It contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is termed as throwing an exception.
Exceptions should be used for exceptional situations outside of the normal logic of a program.
A situation where throwing an exception may be appropriate is when a problem occurs in the middle of a complicated method that would be made even more complicated if it also had to handle unexpected data. The program might throw an exception in order ot "give up" and go back to the caller or to the catch block at the end of the method.
Another example of throwing an exception is when taking user input either from the terminal or via reading a file. If the file cannot be read or an invalid value for the program is encountered, and exception can be thrown. If the file to be read cannot be found, then also an exception is thrown.