During the execution of a program, various conditions can occur that cause an unexpected and abnormal termination of the program.
Example: Consider the following program:
public class TestException {
public static void main (String[] args) {
int falseNumber = Integer.parseInt("OK");
System.out.println("this println statement is not executed");
}
}
the following message is printed on the screen:
Exception in thread "main" java.lang.NumberFormatException: For input string: "OK" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48) at java.lang.Integer.parseInt(Integer.java:468) at java.lang.Integer.parseInt(Integer.java:518) at TestException.main(TestException.java:3)Hence, the string "this println statement is not executed" is not printed.
In Java, the errors that occur at runtime are represented by means of exceptions. Java offers a predefined set of exceptions that can be thrown during program execution.
To avoid that a program terminates unexpectedly, Java allows us to handle exceptions by means of a suitable construct.