Exception handling in Java is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, and others, ensuring that the normal flow of the application is maintained. Java provides a robust framework for handling exceptions using five keywords: try
, catch
, throw
, throws
, and finally
.
Key Concepts
- Exception: An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. Exceptions can be caused by various factors such as invalid user input, network issues, or file I/O errors.
- Exception Handling: This is the process of managing runtime errors to prevent the program from crashing. It involves catching and handling exceptions gracefully.
Types of Exceptions
-
Checked Exceptions: These are exceptions that are checked at compile time. If a method throws a checked exception, it must either handle the exception or declare it using the
throws
keyword. Examples include IOException
and SQLException
.
-
Unchecked Exceptions: These are exceptions that are not checked at compile time. They occur at runtime and include programming bugs such as
NullPointerException
, ArrayIndexOutOfBoundsException
, and ArithmeticException
.
-
Errors: These are serious problems that a reasonable application should not try to catch. Examples include
OutOfMemoryError
and StackOverflowError
.
Exception Handling Mechanisms
1. try-catch Block
The try
block contains the code that might throw an exception. The catch
block handles the exception if it occurs.
try {
int data = 100 / 0;
} catch (ArithmeticException e) {
System.out.println("Exception handled: " + e);
}
2. Multiple catch Blocks
You can use multiple catch
blocks to handle different types of exceptions.
try {
int[] arr = new int[5];
arr[10] = 50;
} catch (ArithmeticException e) {
System.out.println("Arithmetic Exception occurs");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBounds Exception occurs");
} catch (Exception e) {
System.out.println("Parent Exception occurs");
}
3. finally Block
The finally
block contains code that is always executed, whether an exception is thrown or not. It is typically used to release resources like file handles or database connections.
try {
int data = 100 / 0;
} catch (ArithmeticException e) {
System.out.println("Exception handled: " + e);
} finally {
System.out.println("Finally block is always executed");
}
4. throw Keyword
The throw
keyword is used to explicitly throw an exception from a method or any block of code.
public class TestThrow {
static void validate(int age) {
if (age < 18) {
throw new ArithmeticException("Not valid");
} else {
System.out.println("Welcome to vote");
}
}
public static void main(String[] args) {
validate(13);
System.out.println("Rest of the code...");
}
}