Exception Handling
Exception
An exception (or exceptional event) is a problem that arises during the execution of a program.
When an exception occurs, the normal flow of the program is disrupted, and the application
terminates abnormally—which is not desirable. Hence, exceptions should be properly handled.
Exception is an object of throwable class when exception occurs within the method it creates object
and this object is called exception object to handle the runtime exception so that normal flow
applications should be maintained.
Categories of Exceptions in Java
Java exceptions are mainly categorized into three types:
1. Checked Exceptions
These are exceptions checked by the compiler at compile-time.
Also called compile-time exceptions.
These cannot be ignored and must be handled using try-catch or by declaring them using throws.
Example: IOException, SQLException
Checked exceptions ensure robust code and prompt error handling.
2. Unchecked Exceptions
These exceptions occur at runtime and are not checked during compilation.
Also known as runtime exceptions.
These typically result from logic errors or improper API usage.
Example: NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException
The compiler doesn’t require you to catch or declare unchecked exceptions.
Output
Exception Hierarchy
Types of Java Exceptions
1. Built-in Exception
Build-in Exception are pre-defined exception classes provided by Java to handle common errors during
program execution.
1.1 Checked Exceptions
Checked exceptions are called compile-time exceptions because these exceptions are checked at
compile-time by the compiler. Examples of Checked Exception are listed below:
1. ClassNotFoundException: Throws when the program tries to load a class at runtime but the class is
not found because it'sbelong not present in the correct location or it is missing from the project.
2. InterruptedException: Thrown when a thread is paused and another thread interrupts it.
3. IOException: Throws when input/output operation fails
4. InstantiationException: Thrown when the program tries to create an object of a class but fails
because the class is abstract, an interface, or has no default constructor.
5. SQLException: Throws when there's an error with the database.
6. FileNotFoundException: Thrown when the program tries to open a file that doesn’t exist.
1.2 Unchecked Exceptions
The unchecked exceptions are just opposite to the checked exceptions. The compiler will not check
these exceptions at compile time. In simple words, if a program throws an unchecked exception, and
even if we didn't handle or declare it, the program would not give a compilation error. Examples of
Unchecked Exception are listed below:
1. ArithmeticException: It is thrown when there's an illegal math operation.
2. ClassCastException: It is thrown when you try to cast an object to a class it does not belongThis to.
3. NullPointerException: It is thrown when you try to use a null object (e.g. accessing its methods or
fields)
4. ArrayIndexOutOfBoundsException: ThisThis occurs when we try to access an array element with
an invalid index.
5. ArrayStoreException: Thishandle happens when you store an object of the wrong type in an array.
6. IllegalThreadStateException: It is thrown when a thread operation is not allowed in its current state
2.User-Defined Exception
How Does JVM Handle Exceptions?
1. What Happens When an Exception Occurs?
When an exception occurs inside a method:
The method creates an exception object.
This object contains:
o Name of the exception,
o Description/message of the exception,
o Current state of the program (like stack trace),
o Where the exception occurred.
This object is then handed over to the Java Virtual Machine (JVM).
2. Throwing an Exception
Throwing an exception means creating and handling an exception object at runtime.
It interrupts the normal flow of execution.
3. Call Stack Mechanism
The JVM maintains an ordered list of method calls called the call stack.
When an exception occurs, the JVM searches the call stack in reverse order to locate the
appropriate handler.
It looks for the method that contains the try-catch block for the exception.
4. Searching for Exception Handlers
JVM starts from the method where the exception occurred.
It proceeds up the call stack, checking each method for an appropriate exception handler.
If a handler is found, the exception is passed to it.
5. Exception Object Thrown
The type of exception that is thrown depends on:
Output Unhandled:
try block
A try block is used to enclose code that might throw an exception during execution.
To detect and isolate risky code that could throw exceptions (e.g., division by zero, parsing errors).
Enclose code that might throw an exception
It is used within the method
exceptions occur at particular statement in try block rest of code will not executed
it is followed by catch or finally block only
catch Block
To handle exception throws by try block it will not executed if there is no exception inside the try
block.
it is used to handle the exception by declaring the type of exception within the parameter
declared exception must be parent class
it can be used after the try block only
Multiple try-catch Blocks
Multiple catch Blocks
Exception e = new NullPointerException();// it can handle any type of exception
throw block
It is used to throw the user defined or customized exception object to the JVM explicitly for that purpose
we use throw keyword it's also transfer the control from try block to catch block.
Output
throws Block
finally Block
The “finally” block executes after the try/catch block and before the code following try/catch block.
The “finally” block will execute whether the exception is thrown or not.
When an exception is thrown, and no catch block matches the exception even then, the “finally” block
is executed.
When a method returns to the caller from inside the try/catch block via an uncaught exception or an
explicit return statement, the “finally” block gets executed just before the method returns to the caller.
The “finally” block is used to clean up the resources or free the memory used in “try” block.
Example Of User-defined Exception
Output
Differences Between Throw and Throws
Difference Between final finally and finalize in Java
finalize Keyword in Java
The finalize method is a special method of Object class that is called by the garbage collector when an
object is about to be destroyed. The finalize() method can be used to perform any necessary cleanup
operations before the object is destroyed
output