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.
In Java, 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.
On the other hand, an error is when a program does not do what it was intended to do.
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.
Last modified: December 12, 2022
Back to Preconditions And Postconditions