An exception is an event that occurs when a program fails to achieve the normal flow which leads to the termination of that program. In other orders, When a program doesn’t follow rules or constraints defined in Java language then it is said to be an exception.
What happens when an exception occurred?
When an exception is triggered, the method in which it has occurred creates an object, referred as exception object that contains the information of what type of exception this is and state of the program.
After creating an exception object, it hands over to JRE, this stage is termed as throwing an exception.
Now, JRE keeps looking for an appropriate method having a block of codes from call stack (list of methods) to handle that exception called exception handler by tracing back all the way from the method where an error occurred to the appropriate exception handler.
Ones an exception handler is found, the exception object is thrown to that handler, this is known as catching an exception. if no handler is found for it, then the program would be terminated.
Hierarchy of Exception
The throwable class covers entire exception handling in Java.
Throwable class can be classified into two subclasses:-
Exception: An exception which occurs when the problem is specifically triggered by our program and disrupts the normal flow of that program. For example, ArrayOutOfBound exception, I/O exception and more. In other words, an exception is often caused by a program itself. It is recoverable.
An exception can also be divided into two type:-
Unchecked Exception: These exceptions are those exceptions which are not identified at compile time by the compiler. For example, RuntimeException.
Checked Exception: Checked exceptions are those exceptions which are identified at the compile time by the compiler. For example, FileNotFound exception.
Error: An error occurs when the system in which our JRE executes has insufficient resources for our own program. For example, stack overflow. It is not recoverable.
Java is known for its platform-independent feature which is based on the principle of "Write once, Run everywhere". The reason for being platform-independent… Read More
A garbage collector is a program that ensures automatic memory management and runs periodically to recycle unreachable objects. It is responsible for… Read More