When a Java program performs an illegal operation, a special event known as an exception occurs. An exception represents a problem that the compiler was unable to detect before the execution of the program. This is called a run-time error. An example of this would be dividing by zero. The compiler often cannot tell before the program runs that a denominator would be zero at some later point and therefore cannot give an error before the program is run.
-
An exception is an object that holds information about a run-time error. The programmer can choose to ignore the exception, fix the problem and continue processing, or abort the execution of the code. An error is when a program does not do what it was intended to do. Compile time errors occur when the code entered into the computer is not valid. Logic errors are when all the code compiles correctly but the logic behind the code is flawed. Run-time errors happen when Java realizes during execution of the program that it cannot perform an operation.
Java provides a way for a program to detect that an exception has occurred and execute statements that are designed to deal with the problem. This process is called exception handling. If you do not deal with the exception, the program will stop execution completely and send an exception message to the console.
Common exceptions include:
- ArithmeticException
- NullPointerException
- ArrayIndexOutOfBoundsException
- ClassCastException
- IOException
For example, if you try to divide by zero, this causes an ArithmeticException
. Note that in the code section below, the second println()
statement will not execute. Once the program reaches the divide by zero, the execution will be halted completely and a message will be sent to the console:
int numerator = 23;
int denominator = 0;
// the following line produces an ArithmeticException
System.out.println(numerator/denominator);
System.out.println(_This text will not print_);
A NullPointerException
occurs if you use a null reference where you need an object reference. For example,
String name = null;
// the following line produces a NullPointerException
int i = name.length();
System.out.println(_This text will not print_);
Since name
has been declared to be a reference to a String
and has the value null
, indicating that it is not referring to any String
at this time, an attempt to call a method within name
, such as name.length()
, will cause a NullPointerException
. If you encounter this exception, look for an object that has been declared but has not been instantiated.