Why Java Programs Crash
[comp1110-89]
Why Java Programs Crash
[comp1110-89]Generally, programs crash when they try to execute an invalid operation. For example, so far we have seen that a program crashes when we try to access an array at an invalid index (say a negative index or in index larger than or equal to the array's size). Another reason might be that we are trying to divide a number by zero, or to parse an integer from a string that does not represent a number. There are many more potential reasons, some of which are related to things computers simply cannot or should not do, and some of which just relate to things that should not happen within the logic of a particular program.
In many modern programming languages, including Java, all of these kinds of problems are handled through a single exception mechanism. Exceptions are thrown at the point where the program itself or the language runtime detects an error. They then try to find an exception handler, which may execute code in response to the exception, and potentially re-throw it. If no handler is found, the program crashes, and simply prints information about the exception that made it crash.
In Java, exceptions are objects belonging to certain exception classes, for example NumberFormatException or ArrayIndexOutOfBoundsException.
The different classes make it possible to distinguish between different kinds of exceptions, and because exceptions are objects, they can carry relevant data about the particular problem that caused the exception to be thrown.
In general, the exception classes belong to one of three groups:
- Checked Exceptions
This is the standard kind of exception in Java, meant to express both error cases in the normal program logic and certain standard kinds of errors that are common and should usually be handled gracefully. Java is a bit of an outlier among major programming languages in that its compiler enforces that a programmer either handles such exceptions where they can occur or explicitly declares that such exceptions might be thrown within their code.
- Runtime Exceptions
These encompass all exceptions we have seen in the course so far. These are either very special or so common that it would be highly impractical to demand that they be checked or annotated everywhere they could occur, and so get an exemption from the above rule.
- Errors
These are the kinds of problems that might occur in the execution of a program, but are not necessarily the program's fault, and in any case, one cannot reasonably expect that a program can recover from them. Generally, you should not try to handle those.