An exception is an unexpected or unwanted event that disrupt the normal flow of execution.
In general there are three types of errors in java program such as
When the errors arise at the time of compilation known as compile time errors. Basically these errors are syntactical errors in a program that means the user is missing some syntax at the time of writing program. Consider the following example
In this program we are not writing a semicolon at the end of the statement. This syntactical error will be detected by java compiler.
The error arises at the time of execution is known as run-time error. That means sometimes a program may compile successfully but may not execute properly that means error is generating at the time of execution. Such errors are called run-time error. For example;
exception in thread “main” java.lang. noSuchMethodError:main
Runtime errors are detected by JVM.
In the above program JVM cannot execute because it cannot understand the main() method without string args.
These errors are generating by the poor understanding of a program. These errors are detected either by java compiler or JVM. For example, suppose we will write a program to find the area of a square.
the area is 8
We know that the area of a square is a*a but we have written a+a. So we will get wrong result that is 8. This is called as logical error.
Let's see a program to represent an exception.
The above program is syntactically correct so it will compiled successfully but when it will execute , it displays the following message and stops without executing further statement.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:5 at ExceptionDemo.main<ExceptionDemo.java:6>
When JVM will try to execute to access the 5th position data item, it generates an error condition. Then the remaining statement can't execute. As a result program will stop.
Here we observed that an exception is a condition which is caused by a run-time error in the program. When JVM treats an error, it creates an exception object.