Exception is actually a class in Java, and when a program creates an Exception, it creates a new
object, which is an instance of the Exception class. An Exception object can have information about what
went wrong, usually including an error message, and a ???stack trace??? showing which method created the error.
Having created an Exception object when something goes wrong, the program ???throws??? the Exception
using the key word throw. The JVM will print an error message and stop execution when a program throws
an Exception, unless the programmer has provided code to ???catch??? the exception and handle the error
condition in the program. This approach to handling program errors is called ???exception handling??? for obvious
reasons, and it??™s a relatively modern idea.
One advantage of handling errors this way is that code to handle error conditions will be segregated into
code blocks separate from the main logic of the program. This makes it much easier to follow the intent of the
programmer, both in the main logic and in the error handling code.
Java provides many subclasses of Exception so that different problems result in different classes
of Exception objects being thrown. Some examples include FileNotFoundException,
NullPointerException, and NumberFormatException.
Pages:
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232