Think of it as an error. "Your program would have worked except for this error".
An Exception is used by programmers to ensure everything runs smoothly. There are two types of exceptions, a compile-time exception and a run-time exception.
The run time exceptions are classes that extend java.lang.RuntimeException. They do not prevent your code from compiling and running, but rather get thrown if some sort of input is incorrect that can only be found once the program is running. An example of this is an IndexOutOfBoundsException or a NullPointerException.
public void ioobException() {
. . String[] strings = {"zero", "one", "two"};
. . ioobExample(strings);
}
public void ioobExample(String[] strings) {
. . strings[3]; // throws IndexOutOfBoundsExceptions since there is no index 3
}
public void npException() {
. . npeExample(null);
}
public void npeExample(Object value) {
. . value.toString(); // throws NullPointerException because null was passed in
}
Both of those can only be determined at run time, not when the code is written or compiled.
The compile time exceptions prevent your code from even running if you do not handle them correctly. These extend java.lang.Exception or java.lang.Throwable. Typically they are called hard exceptions as you have to put in logic to handle the case that the exception occurs.
The way you do this is
try {
. . // code that can throw the exception
} catch (YourException e) {
. . // code for what you are going to do to mitigate
}
The other option is to add "throws YourException" to your method signature.
Two tips:
1) You should never get a NullPointerException or an IndexOutOfBoundsException. Those are signs you didn't do proper logical handling.
2) Never "swallow" or "absorb" an exception. This means you don't do a try/catch with an empty catch block. An exception should always be handled in a way that provides input as to what was wrong and recovery opperations
3) Never use a try/catch to control the flow of a program. In other words. Do not do:
public boolean isNumber(String numberString) {
. . try {
. . . . Integer.parseInt(numberString);
. . . . return true;
. . catch (NumberFormatException e) {
. . . . return false;
. . }
}
In this case it is better to use a RegEx to determine if the string is a number.