Java Reference
In-Depth Information
To understand how exception handling works in Java, you need to under-
stand the three categories of exceptions:
Checked exceptions. A checked exception is an exception that is typically
a user error or a problem that cannot be foreseen by the programmer.
For example, if a file is to be opened, but the file cannot be found, an
exception occurs. Because this type of exception is a checked exception,
it must be dealt with in Java and cannot simply be ignored (as we will
see when we discuss the Handle or Declare Rule).
Runtime exceptions. A runtime exception is an exception that occurs
that probably could have been avoided by the programmer. As opposed
to checked exceptions, runtime exceptions can be ignored (and should
be, in most cases). You should let a runtime exception crash your pro-
gram, then find the problem and change your code so that the exception
does not arise again. Examples of runtime exceptions include running
off the end of an array, integer division by zero, referencing a null refer-
ence, and casting a reference to an invalid data type.
Errors. Actually, these are not exceptions at all, but problems that arise
beyond the control of the user or the programmer. Errors are typically
ignored in your code because you can rarely do anything about an error,
even if you wanted your program to fix the problem. For example, if a
stack overflow occurs, an error will arise. However, because you are out
of memory, your program will be unable to continue executing. Any code
you have written that attempts to fix the problem won't get a chance to
execute anyway, so errors are often ignored when designing and writing
Java applications.
Even though errors are not exceptions, they behave similarly to exceptions
in terms of the flow of the control when they arise. Both exceptions and errors
can crash your program, as we will now discuss.
Flow of Control of Exceptions
Exceptions in Java are objects that are thrown by a method. When a method is
invoked, it is pushed onto the method call stack. When a method throws an
exception, the method is popped off the call stack, and the exception is thrown
to the previous method on the stack.
For example, suppose that main() is at the bottom of the call stack, followed
by method1() and then method2(). If method2() throws an exception,
method2() is popped off the call stack, and the exception is thrown down to
method1().
Search WWH ::




Custom Search